Read more

Rails I18n fallback locales

Henning Koch
July 28, 2011Software engineer at makandra GmbH

When you need to create a locale for a language variant (like Austrian for German), you probably don't want to duplicate your entire de.yml file only to change a few minor exceptions for our Austrian friends.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Luckily, the I18n gem used by Rails has a fallback feature Show archive.org snapshot where you can make one locale file fall back to another if no translation is available.

In the example above you would have a config/locales/de_DE.yml:

de_DE:
  # hundreds of translations here

... and another locale config/locales/de_AT.yml:

de_AT:
  # only a handful exceptions here

Now write the following lines to config/initializers/i18n.rb to make de_AT fall back to de_DE:

require "i18n/backend/fallbacks"
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
I18n.fallbacks.map('de_AT' => 'de_DE')

Check if a key is defined in the current locale (without fallback)

Do this:

I18n.exists?('my.key', fallback: false)

Rails 2

For Rails 2.3.11 you need to upgrade your project to use the I18n gem by adding this to the top of your Gemfile:

gem 'i18n'

Then run

bundle install
Posted by Henning Koch to makandra dev (2011-07-28 12:51)