richard richard - 1 year ago 59
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

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
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
in an initializer but to no avail.

Oddly enough, if I execute the
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
directive makes the test pass. But it should be possible to do from within an engine initializer I think?

Answer Source

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