【发布时间】: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