8

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?

Community
  • 1
  • 1
richard
  • 14,050
  • 8
  • 37
  • 39
  • I wrote an SO answer on the different ways to add translations, you might want to try creating a specific translation backend and add it using chaining as describes here: http://stackoverflow.com/questions/25386964/how-to-add-values-dynamically-to-i18n/25387302#25387302 – Marc Lainez Jun 29 '16 at 12:44
  • Rails has an after_initialize hook that you can call. Or you can call this in a before_action block in your applications controller. – ekampp Jul 04 '16 at 10:49
  • @EmilKampp it looks like the `after_initialize` actually works from the test I ran just now! As opposed to all the other hooks that I tried. Will try to verify this today. – richard Jul 06 '16 at 08:23
  • Nice. Let me know how that goes. – ekampp Jul 06 '16 at 08:24

1 Answers1

0

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
richard
  • 14,050
  • 8
  • 37
  • 39