开发者

Is it possible to use simultaneously 2 I18n backends and use the second one only as a fallback?

开发者 https://www.devze.com 2023-01-22 15:43 出处:网络
In my Rails application, I would like to use simultaneously 2 backends, the first one storing translations in a DB, and the second one being the default YML based backend. I woud like that this second

In my Rails application, I would like to use simultaneously 2 backends, the first one storing translations in a DB, and the second one being the default YML based backend. I woud like that this second backend serves as a fallback backend, ie if a translation is not found in the first, Rails looks up the translation in the second one.

Is it possible to achieve that?

Edit开发者_开发技巧:

My motivation is I would like not to have to store the default Rails translations in the first backend. The first backend I use comes with an admin web interface that display all the translations contained in the backend, I don't want to clutter this interface with those default translations. And I would like not to have to import them in the first backend, neither to have to update them when there are actualized.


The i18n gem does that and is compatible with rails. Actually it is recommended to use it.

From the rdoc of I18n::Backend::Chain:

Backend that chains multiple other backends and checks each of them when a translation needs to be looked up. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends.

To use the Chain backend instantiate it and set it to the I18n module. You can add chained backends through the initializer or backends accessor:

# preserves the existing Simple backend set to I18n.backend 
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)

The implementation assumes that all backends added to the Chain implement a lookup method with the same API as Simple backend does.

0

精彩评论

暂无评论...
验证码 换一张
取 消