views:

566

answers:

2

Hello,

in an internationalised Rails (2.3.5) app, I'd like to show a translation from the default locale instead of "translation missing" - there's a ticket for it but it seems it's still pending:

https://rails.lighthouseapp.com/projects/8994/tickets/2637-patch-i18n-look-up-a-translation-with-the-default-locale-when-its-missed-with-another-specific-locale

For example (taken from the ticket), with two translation files, en.yml and es.yml:

en:

  hello: 'hello'

  hello_world: 'hello world'



es:

  hello_world: 'hola mundo'

When I execute this code:

I18n.t :hello, :locale => :es

Rails returns "hello" instead of a span with "translation missing".

As the ticket is still pending, how could I implement this functionality? I know I could go through and change all my I18n.t calls to have the :default option, but I'd rather not have to go through all the views if I can avoid it! As it's a patch, I suppose I could apply it to the Rails frozen gems, but I'd rather avoid that if I can.

Any help is greatly appreciated!

Many thanks

Dave

A: 

If you do not want to apply the patch to your Rails gem, you could create your own code containing the patches and mix them with the gem.

When looking at the patch, you need to update the code in two places (the third place is the test part).

The first part (i18n.rb) is a module, so by writing a file containing something like this

module I18n
    @@use_default_locale_on_missing_translation = false
    ...etc...
end

you can add the modified code. The second file (simple.rb) can be updated in a similar way, except it is a class you are updating.

After creating the 2 files containing the modifications, you need to include these two files in application.rb or on a similar location. And the code of the Rails gem should be updated with your custom code.

Veger
+3  A: 

Provided that you use the latest I18n gem, add this to an Initializer:

I18n.backend.class.send(:include, I18n::Backend::Fallbacks)

Then you can add your fallbacks like this:

I18n.fallbacks.map('es' => 'en')
Jimmy Stenke
That's solved the problem (I had to install the i18n gem - I thought it was included in Rails but anyway it's working nicely now, thank you very much for your answer!)CheersDave
fishwebby
The basic functionality is included in rails, but the gem contains much more, like an activerecord backend for instance, and better interpolations and such. And from Rails 3 I think it completely replaces the internal one.
Jimmy Stenke