I have many ymls in my rails app, and i want to put some of them in other service, so that i can call this from multiple places. the response of this call will be a hash.
{"en" :
{"test" :
{"text1" : "hi english"},
{"text2" : "mambo number %{num}"}
},
"es" :
{"test" :
{"text1" : "hi espaniol"},
{"text2" : "mamboes numeros %{num}"}
}
}
is there a way i can load that hash into I18n
translations
like
I18n.add_translations(some_hash)
so i can access them with
I18n.t("test.text1")
I18n.t("test.text2", :num => 5)
how can i achieve it?
The dirty way
You could override the load_translation
method in I18n::Backend::Base through a custom module or gem or -- cough -- monkey patching -- cough -- to fetch the translations from different sources, it feels dirty to me but I guess you could try experimenting with that before going further.
https://github.com/svenfuchs/i18n/blob/master/lib/i18n/backend/base.rb#L13
Changing the I18n Backend
You can create a different I18n Backend that implements the expected behaviour and hook it up to I18n through an initializer. I'm assuming that's how tools like localeapp and phraseapp do it. There is a method just for that in I18n::Config
https://github.com/svenfuchs/i18n/blob/master/lib/i18n/config.rb#L23
So you can just do this in an initializer
I18n.backend = MyAwesomeI18nBackend.new
The good thing is that you can chain multiple backends together
I18n.backend = I18n::Backend::Chain.new(MyAwesomeI18nBackend.new)
It makes sure you still have access to the default translation backends or other custom backends.
References
Ryan made a great railscast back in the days explaining how to change backends. It's a bit outdated but it gives you a good idea of what needs to be done.
I18n Backends
If your translations are related to some data saved in a database, you could also use globalize to handle those.
https://github.com/globalize/globalize
EDIT: Simpler way by Dima
If you have a hash, you can use the default backend's store_translation
method to load translations from that hash.
I18n.backend.store_translations(:en, {test: "YOOOOOHHHHHOOOO"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With