Add translation to I18N dynamically

回眸只為那壹抹淺笑 提交于 2019-12-25 01:45:04

问题


I have added humanized-money-accessors as described here: Decimals and commas when entering a number into a Ruby on Rails form

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.

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.


回答1:


You might want to check out globalize3 gem. You have railscast tutorial http://railscasts.com/episodes/338-globalize3?view=asciicast.




回答2:


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.



来源:https://stackoverflow.com/questions/17072424/add-translation-to-i18n-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!