I18n自定义异常处理程序不是用`t`调用的,只能用`I18n.translate`调用

时间:2015-03-25 12:03:08

标签: ruby-on-rails rails-i18n

我有这个自定义异常处理程序:

module I18n
  class MissingTanslationsCollectorExceptionHandler < I18n::ExceptionHandler
    # Handles exceptions from I18n
    def call(exception, locale, key, options)
      if exception.is_a?(I18n::MissingTranslation)
        binding.pry
        missing_translations << I18n.normalize_keys(locale, key, options[:scope])
        super
      end
    end
  end
end

我这样分配:

I18n.exception_handler = I18n::MissingTanslationsCollectorExceptionHandler.new

使用控制台时,它似乎有效:

$ rails c
Loading development environment (Rails 4.2.0)

[1] base »  I18n.exception_handler
=> #<I18n::MissingTanslationsCollectorExceptionHandler:0x00000101c121e8>
[2] base »  I18n.translate 'unknown'

From: /Users/josh/Documents/Work/MuheimWebdesign/base/src/lib/missing_i18n_exception_handler.rb @ line 11 I18n::MissingTanslationsCollectorExceptionHandler#call:

    10:   if exception.is_a?(I18n::MissingTranslation)
 => 11:     binding.pry
    12:     missing_translations << I18n.normalize_keys(locale, key, options[:scope])

[1] base(#<I18n::MissingTanslationsCollectorExceptionHandler>) »  c
=> "translation missing: en.unknown"

但是,当启动服务器并使用t 'unknown'点击缺失的翻译时,binding.pry未被调用。只有在执行I18n.translate unknown`时才会调用它。为什么呢?

也许这与使用Capybara在自己的进程中运行功能规范这一事实有关?

更新

以下是有问题的Rails应用: https://github.com/jmuheim/base/tree/features/custom-i18n-exception-handler

我在这里添加了自定义i18n异常处理程序: https://github.com/jmuheim/base/commit/f2aff30046c7a9f38c4a1faed0953e474099120c

我添加的代码应该在这里展示问题: https://github.com/jmuheim/base/commit/af484b6b96f41194043e0ad0668a5c288d4a0af3

只需转到root_path,然后它就会被触发(一次,而不是两次!)。

2 个答案:

答案 0 :(得分:2)

这是因为ActionView t不是I18n.translate的简单别名。除此之外,它还会将任何MissingTranslation例外转换为HTML中的范围。

有关详细信息,请参阅code

我希望例外能够冒泡,但每次我在视图中调用rescue_format: true时,我都不想指定t,所以我将Rails的帮助程序改为始终将rescue_format: true作为选项传递。

另外需要注意的是:翻译助手已从一个Rails版本更改为下一个版本,因此请务必阅读您的版本的实际代码以了解该怎么做。

答案 1 :(得分:-1)

如果您在应用程序中使用区域设置语言,则可能是{locale} .yml文件中的语法错误。

您可以在以下链接中验证您的yml文件。

http://www.yamllint.com/

我希望它可以提供帮助。