如何判断是否在模块名称空间而不是全局名称空间中定义了常量? [英] How to judge whether a Constant has been defined within a module namespace, not a global one?
问题描述
我有两个同名的const;一个是全局const,另一个是在名称空间Admin下定义的.但是我需要区分它们;全局对象已经定义,而范围对象还需要自动定义(如果尚未定义):
I have two Const with the same name; One is a global const, and the other is defined under the namespace Admin. But I need to distinguish them;The global one has already defined, and the scoped one need to auto defined if it has not been defined yet:
A = 'A Global Const'
module Admin
A = 'A Const within the Admin namespace' if const_defined? 'A' # always true and the Admin::A can never be defined!
end
puts A # => 'A Global Const'
puts Admin::A # => NameError: uninitialized constant Admin::A
# the Admin::A will never be defined.
但是,如果定义了全局A,则"const_defind?"部分将永远返回真相!
我什至尝试过:
But if the Global A is defined, the "const_defind?" part will always return ture!
I even have tried:
... if defined? A
... if self.const_defined? 'A'
... if Object.const_get('Admin').const_defined? 'A'
总是如此!
我需要区分它们,因为我需要在A和Admin :: A两种形式中使用A;
类似于PostsController供公众使用的情况,以及Admin :: PostsController供管理员使用的情况;
帮助!
Always true!
I need to distinguish them because I need to use the A in A and Admin::A two forms;
Like the situation PostsController for public use, and Admin::PostsController for admin use;
Help!
推荐答案
实际上,const_defined?
和const_get
遍历了层次结构,对于模块而言,该层次结构包括(
Indeed, const_defined?
and const_get
go through the hierarchy, which for modules include (artificially) the Object
class. You can use Module#constants
to avoid this, though:
module Admin
A = 'A Const with in the Admin namespace' unless constants.include?(:A)
end
注意:在Ruby 1.8中,您要检查"A"
,而不是:A
Note: In Ruby 1.8, you check against "A"
, not :A
这篇关于如何判断是否在模块名称空间而不是全局名称空间中定义了常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!