richard richard - 4 months ago 17
Ruby Question

Dynamically loading I18n translations from gem into Rails Engine

I've created a gem (TranslationsGem) which I use in multiple projects (an engine and a Rails app). This gem sets up several hashes which are loaded into the I18n backend.

A method

#store_dynamic_translations
sets up several hashes which are loaded into the I18n backend. It basically works like this:

I18n.backend.store_translations(:en, { test: { property: 'value' } })


My tests confirm the method and translation loading works correctly. I can't however get it to work in the host engine and Rails app.
In my test environment I have to execute the method in my
test_helper
to ensure the translations are loaded correctly. Outside the test environment I cannot seem to get it working correctly. I can verify that the method is executed, but the translations aren't loaded.

I have tried numerous things for hours, like executing the method in the Engine initializer and using ActiveSupport hooks. In the host Rails app I tried executing the
#store_dynamic_translations
in an initializer but to no avail.

Oddly enough, if I execute the
#store_dynamic_translations
in my Rails app controller or view, it works. Is there any way to set this up at app boot time?




EDIT: I've setup an example repository which contains the current setup.


  1. A Gem which dynamically stores translations into the I18n backend.

  2. A Rails Engine which loads the gem and should have its translations available



In the test in question uncommenting the
MyI18n::Translations.store_dynamic_translations
directive makes the test pass. But it should be possible to do from within an engine initializer I think?

Answer

As per Emill Kampp's suggestion, the correct hook was after_initialize. I specified this in engine.rb:

module Blorgh
  class Engine < ::Rails::Engine
    isolate_namespace Blorgh

    config.after_initialize do
      MyI18n::Translations.store_dynamic_translations
    end
  end
end
Comments