【问题标题】:Rails i18n: Can I turn off "translation missing" errors?Rails i18n:我可以关闭“翻译缺失”错误吗?
【发布时间】:2011-03-04 22:34:38
【问题描述】:

我有一个多租户应用程序,我正在尝试使用 i18n gem 来允许我们的每个客户根据自己的喜好自定义系统、更改不同页面上的文本、自定义电子邮件等等。诚然,我并没有按照预期使用 i18n,因为我实际上并没有翻译不同的“语言”,所有内容都是英文的,但如果有意义的话,每个客户都有不同的英文。

不过,我在 i18n gem 中遇到了一个我认为非常糟糕的设计决策:如果不存在翻译,而不是简单地不进行翻译并打印出正常情况下的任何内容,它会引发错误。例如,

<%= distance_of_time_in_words_to_now @press_release.submitted_at %>

出来

translation missing: en, datetime, distance_in_words, x_days

我的意思是,来吧!我什至不想翻译它。

我知道发生这种情况的原因是因为我没有加载默认翻译,但我使用 ActiveRecord 作为后端并且我想保持它干净。 “解决方案”是将所有 yaml 翻译文件导入我的数据库翻译存储中,但这似乎不是一个好主意。如果我将来升级 Rails 会怎样?我将不得不担心使所有这些翻译保持同步。

同样,我无法理解为什么这是默认行为。什么时候会有人希望显示那个时髦的错误消息,而不是只使用默认的“3 天前”?

无论如何,我的问题是,如果翻译不存在,有没有办法让它自动关闭翻译并使用未翻译的消息?谢谢!

【问题讨论】:

    标签: ruby-on-rails internationalization


    【解决方案1】:

    这似乎可以解决问题。

    require 'i18n' # without this, the gem will be loaded in the server but not in the console, for whatever reason
    
    # store translations in the database's translations table
    I18n.backend = I18n::Backend::ActiveRecord.new
    
    # for translations that don't exist in the database, fallback to the Simple Backend which loads the default English Rails YAML files
    I18nSimpleBackend = I18n::Backend::Simple.new
    I18n.exception_handler = lambda do |exception, locale, key, options|
      case exception
      when I18n::MissingTranslationData
        I18nSimpleBackend.translate(:en, key, options || {})
      else
        raise exception
      end
    end
    

    【讨论】:

    • 你会把这个放在哪里?
    • 可能在config/initializers/下的.rb文件中。
    • I18n.backend = I18n::Backend::ActiveRecord.new 在 Rails 4.2 中导致未初始化的 const 错误
    【解决方案2】:

    如果您对使用默认异常处理程序处理其他异常感兴趣,Philip Brocoum 的 答案中的修改后的代码应该可以解决问题(Rails 3.2.2 版本):

    i18n_simple_backend = I18n::Backend::Simple.new
    old_handler = I18n.exception_handler
    I18n.exception_handler = lambda do |exception, locale, key, options|
      case exception
      when I18n::MissingTranslation
        i18n_simple_backend.translate(:en, key, options || {})
      else
        old_handler.call(exception, locale, key, options)
      end
    end
    

    此代码将允许您仅捕获需要以不同方式处理的异常。

    【讨论】:

    • 在 Rails 4.2 中。 i18n_simple_backend.translate(:en, key, options || {}) 导致错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多