Dynamically loading I18n translations from gem into Rails Engine
Asked Answered
F

1

9

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?

Fideicommissum answered 25/6, 2016 at 18:37 Comment(4)
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: #25387464Shaffer
Rails has an after_initialize hook that you can call. Or you can call this in a before_action block in your applications controller.Heterotypic
@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.Fideicommissum
Nice. Let me know how that goes.Heterotypic
F
1

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
Fideicommissum answered 7/7, 2016 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.