覆盖rails transper helper

时间:2014-10-13 10:56:06

标签: ruby-on-rails ruby-on-rails-4 locale override rails-i18n

我希望I18n.translate()I18n.t()使用特定的区域设置,而不是 I18n.locale 。 我不想每次都使用I18n.t(:my_key, locale: :my_locale),所以如果我可以覆盖函数本身就会很棒。

我试着把它放在一个新的帮手中:

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

这适用于像t('word')这样的“硬键”,但找不到t('.title')这样的“动态键”的正确路径,它应该使用我的部分路径,即{{ 1}}。

感谢您的帮助!

2 个答案:

答案 0 :(得分:7)

似乎在以下功能之间存在一些混淆:

I18n.translate不执行"懒惰查找" (即,将查找键的范围限定为当前的部分,如果它以点开头),这是您期望的。这是ActionView::Helpers::TranslationHelper#translate的一项功能,以及some others

您的方法覆盖了ActionView::Helpers::TranslationHelper#translate,而没有调用super来延迟加载。所以,如果你想继续覆盖这个方法,我想你可能想要:

# 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

就个人而言,我宁愿每次在我的视图中使用t(:my_key, locale: :my_locale)而不使用覆盖,或者最多只有一个单独的帮助方法来包含对ActionView::Helpers::TranslationHelper#translate的额外业务的调用强制特定语言环境的逻辑。

答案 1 :(得分:1)

您可以尝试下一步:

配置/初始化/ 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

如果你需要定义几个模块函数,那么每次使用下一个构造更容易,而不是module_function

module I18n
  extend(Module.new do
    def german
      ...
    end

    def english
      ...
    end

    def japaneese
      ...
    end
  end)
end
相关问题