Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to judge whether a Constant has been defined within a module namespace, not a global one?

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!

like image 605
Croplio Avatar asked Jan 22 '23 16:01

Croplio


1 Answers

You should try scoping both of them to test just 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"
like image 56
Paul Rubel Avatar answered Jan 24 '23 05:01

Paul Rubel