LoginSignup
0
1

More than 5 years have passed since last update.

Railsでi18nの値からキーを取得する方法

Posted at

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されていないことがあるので半ば強引に定数化してみた。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1