0

我正在尝试为 I18n gem 编写一个自定义异常处理程序,它将覆盖默认的“翻译丢失”错误,并在特殊情况下抛出嘈杂的异常,例如当缺少语言环境和缺少顶级命名空间时。缺少语言环境只是检查 if 的问题available_locales.include?(locale),但是我如何查看是否定义了命名空间?本质上,我想要以下功能:

def caption
  begin
    I18n.t("event.welcome", :locale => :en)
  rescue MissingNamespace # should be thrown when "event" doesn't exist as a key under :en, (I18n would normally overspecify and say that "event.welcome" as a full key doesn't exist"
    "Namespace is missing"
  rescue
    #other stuff
  end
end

有没有办法做到这一点?或者我只能根据一个键查找?

4

1 回答 1

0

这是诀窍:

module I18n
  def namespace_missing?(locale, key)
    namespace = key.split(".")[0] # assuming you want the top level namespace
    !backend.send(:translations)[locale][namespace] # this presupposes locale exists
  end
end

...然后你可以把它扔到你的异常处理程序中

于 2012-06-19T01:18:32.560 回答