如何判断Constant是否已定义在模块命名空间内,而不是全局的?
我有两个同名的常量;一个是全局常量,另一个是在命名空间 Admin 下定义的。但我需要区分它们;全局的已经定义了,作用域的如果尚未定义则需要自动定义:
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?”部分将始终返回 ture!
我什至尝试过:
... if defined? A
... if self.const_defined? 'A'
... if Object.const_get('Admin').const_defined? 'A'
永远正确!
我需要区分它们,因为我需要使用 A 和 Admin::A 两种形式中的 A;
就像公共使用的 PostsController 和管理员使用的 Admin::PostsController 的情况;
帮助!
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.
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'
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该尝试确定两者的范围以仅测试您想要的一个
You should try scoping both of them to test just the one you want
事实上,
const_define?
和const_get
遍历层次结构,对于模块来说包括(人为)Object
类。不过,您可以使用 Module#constants 来避免这种情况:注意:在 Ruby 1.8 中,您检查的是
"A"
,而不是:A
Indeed,
const_defined?
andconst_get
go through the hierarchy, which for modules include (artificially) theObject
class. You can useModule#constants
to avoid this, though:Note: In Ruby 1.8, you check against
"A"
, not:A
使用其
#class
或#to_s
或#inspect
可以帮助您了解您定义的对象是否实际上是全局的。Using its
#class
or#to_s
or#inspect
may help you know if your defined object is actually global or not.