i18nに指定した値からモデルだったり属性物理名を取りたかったので書いてみた。
ja:
activerecord:
models:
users: "ユーザ"
attributes:
users:
id: "ユーザID"
email: "メールアドレス"
def translated
@translate ||= begin
translate = {}
I18n.config.load_path.grep(/#{I18n.locale}\.yml$/).each do |file|
yaml = YAML.load_file(file)[I18n.locale.to_s]
next unless yaml.key?('activerecord')
translate.update(yaml['activerecord'])
end
translate
rescue => e
raise e
end
end
def get_model(model_name)
translated['models'].invert[model_name].camelize.constantize
rescue => e
raise "Cannot found model name '#{model_name}' at #{I18n.config.load_path.grep(/#{I18n.locale}\.yml$/)}."
end
def get_attribute_for(model, attribute_name)
translated['attributes'][model.name.underscore].invert[attribute_name]
rescue => e
raise "Cannot found attribute '#{attribute_name}' for '#{model.name}' at #{I18n.config.load_path.grep(/#{I18n.locale}\.yml$/)}."
end
p model = get_model('ユーザ')
#=> User(id: integer, email: string)
p get_attribute_for(model, 'メールアドレス')
#=> "email"
ActiveRecord::Base.subclasses
から引くことも考えたが、タイミングによってはrequireされていないことがあるので半ば強引に定数化してみた。