marc
marc

Reputation: 151

Is it possible to make rails i18n locales fallback to each other?

I'm using Rails 3 with Globalize3 0.2.0.beta4

Ideally I need :fr to fallback to :en and vice versa.

There are cases when only a French translation is available and I need to show it even if the locale is :en.

I tried

config.i18n.fallbacks = { :fr => :en, :en => :fr }

but somewhat unsurprisingly it causes a stack level too deep error.

Upvotes: 8

Views: 3301

Answers (5)

Paweł Gościcki
Paweł Gościcki

Reputation: 9594

In latest i18n gem (0.7.0) I have found it necessary to define fallback locales like this (in config/application.rb):

# Custom I18n fallbacks
config.after_initialize do
  I18n.fallbacks = I18n::Locale::Fallbacks.new(at: :"de-DE", ch: :"de-DE", gb: :"en-US")
end

You also need to set config.i18n.fallbacks = true in all config/environments/*.rb files.

Upvotes: 0

Claudio Shigueo Watanabe
Claudio Shigueo Watanabe

Reputation: 1003

This seems to have changed to this:

Globalize.fallbacks = {:en => [:en, :fr], :fr => [:fr, :en]}

Got from the official docs: https://github.com/globalize/globalize#fallback-locales-to-each-other

Upvotes: 0

jay
jay

Reputation: 12495

I'm changing my answer.

To enable fallbacks, add the following to your environment.rb file:

 #support for locale fallbacks
 require "i18n/backend/fallbacks"
 I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)

Then, you can enable circular fallbacks like you were trying to, eg:

   config.i18n.fallbacks = {'en' => 'fr', 'fr' => 'en'}

In this case, if something is missing in the en locale, it'll check the fr locale, and then the other way around. I don't get any errors running this.

Source: http://batsov.com/articles/2012/09/12/setting-up-fallback-locale-s-in-rails-3/

Upvotes: 5

marc
marc

Reputation: 151

In the end I monkey patched Globalize3. Not great as I have to update the patch whenever the site needs a new locale, but hey, it worked.

module Globalize

  class << self

    def fallbacks(locale = self.locale)
      case locale
      when :en then [:en, :fr]
      when :fr then [:fr, :en]
      end
    end

  end
end

Upvotes: 1

Simon Perepelitsa
Simon Perepelitsa

Reputation: 20639

If you pass an array of locales they will be set as default fallbacks for all locales.

config.i18n.fallbacks = [:en, :fr]

Unfortunately, I haven't found a way to set up just two locales to fall back to each other.

Upvotes: 1

Related Questions