动态地将翻译添加到I18N [英] Add translation to I18N dynamically
问题描述
I have added humanized-money-accessors as described here: Decimals and commas when entering a number into a Ruby on Rails form
现在,在我的模型中,对于相同类型的数据,我有两个属性:原始版本和人类可读的版本.问题:由于我使用的是activerecord-translation-yml-files,因此我必须对原始属性和humanized_attribute进行相同的翻译,因为我的表单显示的是thihumanized_attribute的名称,但是在验证错误时,原始名称就是原始名称属性显示.
Now I have two attributes in my model for the same type of data: the original version and the human-readable version. The problem: Since I am using activerecord-translation-yml-files, I have to put in the same translation for original attribute and the humanized_attribute, because my forms show the name of thie humanized_attribute, but on validation errors, the name of the original attribute is shown.
是否可以动态添加翻译?这样,我可以在调用humanized_accessor-class-method时为字段的humanized-version添加翻译,从而从yml文件中获取原始翻译字符串,而不是将它们(具有相同的值)都写入yml文件,只是为了有更多的DRY.
Is it possible to add translations dynamically? This way I could add the translation for the humanized-version of the field when the humanized_accessor-class-method is called, getting the original translation string from the yml file, instead of writing both of them (with the same value) into the yml-file, just to have more DRY.
推荐答案
This is dependent on the I18n
gem's internal API not changing but it is possible using I18n.backend.store_translations
.
这个人为的例子演示了:
This contrived example demonstrates:
I18n.with_locale(:fake_locale) { I18n.t('some_word') }
=> "translation missing: fake_locale.some_word"
I18n.backend.store_translations(:fake_locale, some_word: 'fake translation')
I18n.with_locale(:fake_locale) { I18n.t('some_word') }
=> "fake translation"
重要:这仅在内存中完成.需要一些持久性或重新生成机制,以防止在重新部署/重新启动服务器时这些消失或消失.
Important: This is only done in memory. Some persistence or re-generation mechanism is necessary to prevent these from disappearing when you redeploy/restart the server.
这篇关于动态地将翻译添加到I18N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!