【问题标题】:How to determine the presence of an I18n namespace in Ruby如何确定 Ruby 中是否存在 I18n 命名空间
【发布时间】:2012-06-18 19:38:22
【问题描述】:

我正在尝试为 I18n gem 编写一个自定义异常处理程序,该处理程序将覆盖默认的“翻译缺失”错误,并在特殊情况下抛出嘈杂的异常,例如当语言环境缺失和顶级命名空间缺失时。缺少语言环境只是检查是否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

有没有办法做到这一点?还是只能根据键查找?

【问题讨论】:

    标签: ruby-on-rails ruby internationalization


    【解决方案1】:

    这是诀窍:

    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
    

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

    【讨论】:

      猜你喜欢
      • 2014-03-08
      • 2017-05-01
      • 2013-09-10
      • 1970-01-01
      • 2021-10-26
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      相关资源
      最近更新 更多