I want I18n.translate() or I18n.t() to use a specific locale, but not I18n.locale.
I don't want to use I18n.t(:my_key, locale: :my_locale) every time, so it would be great if I could override the function itself.
I tried to put 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 fine for "hard keys" like t('word'), but doesn't find the right path for "dynamic keys" like t('.title'), which should use the path of my partial, i.e. de.users.form.title.
Thanks for any help!
It would seem that there is some confusion between the functionalities of:
I18n.translate, from the I18n gem and ActionView::Helpers::TranslationHelper#translate, from RailsI18n.translate does not perform the "lazy lookups" (ie scoping the lookup key to the current partial if it begins with a dot) that you are expecting. That is a feature of ActionView::Helpers::TranslationHelper#translate, along with some others.
Your method is overriding ActionView::Helpers::TranslationHelper#translate, without a call to super to get lazy loading. So, if you want to persist on overriding the method, I think you may want:
# my_helper.rb
module MyHelper
def translate(key, options = {})
# If you don't want to ignore options[:locale] if it's passed in,
# change to options[:locale] ||= MY_LOCALE
options[:locale] = MY_LOCALE
super(key, options)
end
alias :t :translate
end
Personally though, I'd rather use t(:my_key, locale: :my_locale) every time in my views without the override, or at most have a separate helper method that wraps around a call to ActionView::Helpers::TranslationHelper#translate with the extra business logic of forcing a specific locale.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With