Override Rail Assistants

I want I18n.translate() or I18n.t() use a specific language, but not I18n.locale. I do not want to use I18n.t(:my_key, locale: :my_locale) every time, so it would be great if I could override this function.

I tried putting it in a new helper:

 # my_helper.rb module MyHelper def translate(key, options = {}) options[:locale] = MY_LOCALE I18n.translate key, options end alias :t :translate end 

This works great for hard keys like t('word') , but does not find the correct path for 'dynamic keys', for example t('.title') , which should use my partial path, i.e. de.users.form.title .

Thanks for any help!

+6
source share
2 answers

It would seem that there is some confusion between the functionality:

I18n.translate does not perform "lazy searches" (for example, it scans the search key to the current partial, if it starts with a period), which you expect. This is a feature of ActionView::Helpers::TranslationHelper#translate , as well as some others .

Your method overrides ActionView::Helpers::TranslationHelper#translate , without calling super to get a lazy load. So, if you want to continue to override the method, I think you can:

 # my_helper.rb module MyHelper def translate(key, options = {}) # If you don't want to ignore options[:locale] if it passed in, # change to options[:locale] ||= MY_LOCALE options[:locale] = MY_LOCALE super(key, options) end alias :t :translate end 

Personally, I prefer to use t(:my_key, locale: :my_locale) each time in my views without overriding or, at most, have a separate helper method that goes around calling ActionView::Helpers::TranslationHelper#translate using additional business logic force a specific locale.

+6
source

You can try the following:

configurations / Initializers / i18n.rb

 module I18n def german(*args) options = args.last.is_a?(Hash) ? args.pop.dup : {} args << options.merge(locale: :de) translate(*args) end module_function :german end 

And if you need to define several module functions, it will be easier to use the following construct instead of module_function each time:

 module I18n extend(Module.new do def german ... end def english ... end def japaneese ... end end) end 
0
source

Source: https://habr.com/ru/post/976666/


All Articles