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

15

我有一个多租户应用程序,正在尝试使用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个回答

7
如果您想使用默认异常处理程序来处理其他异常,那么从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 || {})会导致错误。 - user938363

7
这似乎能解决问题。
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

2
你会把这个放在哪里? - Kenny Meyer
2
可能在 config/initializers/ 目录下的 .rb 文件中。 - Dimitar
1
I18n.backend = I18n::Backend::ActiveRecord.new 在 Rails 4.2 中会导致未初始化常量错误。 - user938363

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接