Search code examples
ruby-on-railslocale

How can I override locale values with custom values in Rails?


In my en.yml locale file (config/locales/en.yml), I have

en:
  settings:
    updated: 'Your settings have been updated.'

Sometimes, I want to override settings.updated with other text but still use the en locale.

I've tried the following, but settings.updated is not being overwritten:

locale_overrides = {"settings"=>{"updated"=>"override text"}}
I18n.backend.store_translations(I18n.locale, {"settings"=>{"updated"=>"override text"}})

p locale_overrides['settings']['updated']
p I18n.t('settings.updated')

assert I18n.t('settings.updated') == locale_overrides['settings']['updated']

and the following prints to the console:

"override text"
"Your settings have been updated."

Any ideas what I'm doing wrong or how to correctly overwrite locale settings?

UPDATE

Looks like this is happening because, as the documentation states,

The backend will lazy-load these translations when a translation
is looked up for the first time.

Solution

  • I ended up using Chaining with a KeyValue backend:

    key_value_i18n_backend = I18n::Backend::KeyValue.new(locale_overrides_hash)
    I18n.backend = I18n::Backend::Chain.new(key_value_i18n_backend, I18n.backend)