【问题标题】:Check if a namedspaced class exists检查命名空间类是否存在
【发布时间】:2014-03-11 14:04:30
【问题描述】:

我正在编写一个帮助程序来检查给定的类是否存在。

def safe_constant(constant_sym)
  return Object.const_get(constant_sym) if Object.const_defined? constant_sym
end

这适用于safe_constant(:User) 之类的东西

但是,我们有许多在模块中命名空间的对象

safe_constant(:Admin::User) 显然不是一个有效的符号。我知道我可以通过以下方式确定这是否存在:

Object.const_get(:Admin).const_get(:User) 但在我开始编写某种拆分循环向下钻取方法来获取最终常量之前,是否已经有任何标准方法来处理这个问题?

【问题讨论】:

  • 接受类名作为符号是硬性要求吗?因为将其作为字符串进行测试要容易得多:Object.const_get('Admin::User') rescue nil.
  • 我最初尝试这样做,但它给出了错误:wrong constant name Admin::User

标签: ruby constants


【解决方案1】:

根据 Ruby API 文档,可以让 const_defined?const_get 与命名空间字符串一起检查并返回类常量。需要做的是将第二个参数(inherit)传递为false,例如:

class User; end

module Admin
  class User; end
end

Object.const_defined?('Admin::User', false) # => true

Object.const_get('Admin::User', false) # => Admin::User

PS:const_defined?const_get 不接受命名空间的 Symbol 会引发 NameError 异常,例如:

# namespaced String
Object.const_defined?('Admin::User', false) # => true

# namespaced Symbol
Object.const_defined?(:'Admin::User', false)
# => NameError (wrong constant name Admin::User)

【讨论】:

    【解决方案2】:

    这样的事情怎么样?

    def safe_constant(constant_sym)
      return constant_sym.to_s.constantize if valid_constant? constant_sym.to_s
    end
    
    
    def valid_constant?(const)
      const.constantize
      return true
    rescue NameError
      return false
    end
    

    【讨论】:

    • 请注意,constantize 方法来自 activesupport gem。
    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 2013-10-03
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多