2010-06-17 54 views
10

我有一个多租户应用程序,我正在尝试使用i18n gem来允许我们的每个客户根据自己的喜好自定义系统,更改各种页面上的文本,自定义电子邮件等等。无可否认,我并没有使用i18n,因为我并没有真正翻译不同的“语言”,所有东西都是英文的,但如果有意义的话,每个客户都有不同的英文。Rails i18n:我可以关闭“翻译缺失”错误吗?

尽管如此,我还是遇到了一个我认为是国际宝石宝石中糟糕的设计决定:如果翻译不存在,而不是简单地不翻译和打印任何它通常会打印的东西,它会引发一个错误。例如,

<%= distance_of_time_in_words_to_now @press_release.submitted_at %> 

出来作为

translation missing: en, datetime, distance_in_words, x_days 

我的意思是,来吧!我甚至不希望被翻译。

据我所知,这是因为我没有加载默认翻译,但我使用ActiveRecord作为后端,我想保持清洁。 “解决方案”是将所有yaml翻译文件导入到我的数据库翻译库中,但这似乎不是一个好主意。如果我将来升级导轨会怎么样?我将不得不担心保持所有这些翻译同步。

同样,我无法理解为什么这是默认行为。 ANYBODY什么时候想让这个时髦的错误消息出现,而不是仅仅使用默认的“3天前”?

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

回答

6

这似乎是个伎俩。

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

你究竟在哪里放置它? – 2011-09-06 23:28:50

+2

可能位于'config/initializers /'下的'.rb'文件中。 – Dimitar 2011-09-28 18:20:51

+1

Rails 4.2中的'I18n.backend = I18n :: Backend :: ActiveRecord.new'会导致未初始化的const错误 – user938363 2015-07-04 14:45:32

7

如果你有兴趣在处理其他异常使用默认的异常处理程序,从菲利普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 

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

+0

In Rails 4.2。 'i18n_simple_backend.translate(:en,key,options || {})'会导致错误 – user938363 2015-07-04 14:46:29