This is fairly obvious, but I thought I’d share since I haven’t seen
quite this solution mentioned elsewhere.
I wanted some way to map a locale (e.g. :en) to the language name
(e.g. “English”) for a select box. Rather than stick the info in a
database, hash or some other separate record, I put it in the YML file
of the locale itself:
# config/locales/en.yml en: meta: language_name: 'English'
Then made an I18n method to read it:
# config/initializers/i18n.rb module I18n def self.name_for_locale(locale) begin I18n.backend.translate(locale, "meta.language_name") rescue I18n::MissingTranslationData locale.to_s end end end
Used like this:
I18n.name_for_locale(:en) # => "English"
As a gist here if you want to fork and improve:
Can anyone see issues with this? I just started using Rails i18n the
other day, so I may well be missing something.
Perhaps it would be a good idea to add this info (but with a better
keyâ€¦ meta.name? language.name?) to all translations in the rails-i18n