Add translation to I18N dynamically

2019-09-17 00:18发布

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.

2条回答
仙女界的扛把子
2楼-- · 2019-09-17 00:33

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

查看更多
爷的心禁止访问
3楼-- · 2019-09-17 00:35

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.

查看更多
登录 后发表回答