How to determine if a constant has been defined in the module namespace, and not global?

I have two Const with the same name; One of them is the global const, and the other under the name Admin. But I need to distinguish them: the global is already defined, and the scope should be automatically determined if it is not already defined:


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 global A is defined, "const_defind?" part will always be returned!
I even tried:


 ... if defined? A ... if self.const_defined? 'A' ... if Object.const_get('Admin').const_defined? 'A' 

Always right!
I need to distinguish them because I need to use A in and Admin :: A two forms,
Similar to the PostsController situation for general use and Admin :: PostsController for use by the administrator,
Help!

+4
source share
3 answers

Really const_defined? and const_get pass a hierarchy, which for modules includes the ( artificially ) class Object . You can use Module#constants to avoid this:

 module Admin A = 'A Const with in the Admin namespace' unless constants.include?(:A) end 

Note. In Ruby 1.8 you check for "A" , not :A

+3
source

You should try looking at both of them to check only the one you want.

 module Adm A = "FOO" end defined?(A) # -> nil defined?(Adm::A) # "constant" defined?(::A) # -> nil A = "BAR" defined?(::A) # -> "constant ::A # => "BAR" Adm::A # => "FOO" 
+6
source

Using #class or #to_s or #inspect can help you find out if your specific object is global or not.

0
source

All Articles