代码之家  ›  专栏  ›  技术社区  ›  Philip Brocoum

rails i18n:我可以关闭“翻译丢失”错误吗?

  •  11
  • Philip Brocoum  · 技术社区  · 16 年前

    我有一个多租户的应用程序,我正在尝试使用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天前”?

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

    2 回复  |  直到 14 年前
        1
  •  7
  •   Pawel Barcik    14 年前

    如果您对使用默认异常处理程序处理其他异常感兴趣,请使用 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
    

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

        2
  •  6
  •   Philip Brocoum    16 年前

    这似乎起到了作用。

    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