我有一个多租户应用程序,我正在尝试使用 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 天前”?
无论如何,我的问题是,有没有办法让它自动关闭翻译并在翻译不存在时使用未翻译的消息?谢谢!
这似乎可以解决问题。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)