簡體   English   中英

如何判斷是否已在模塊命名空間中定義了Constant,而不是全局?

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

我有兩個同名的Const; 一個是全局const,另一個是在命名空間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?” 部分將永遠回歸!
我甚至嘗試過:


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

總是如此!
我需要區分它們,因為我需要使用A中的A和Admin :: A兩種形式;
像PostsController一樣供公眾使用,Admin :: PostsController供管理員使用;
救命!

你應該嘗試確定它們的兩個范圍來測試你想要的那個

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"

確實, const_defined? const_get遍歷層次結構,模塊包括( 人工Object類。 但是,您可以使用Module#constants來避免這種情況:

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

注意 :在Ruby 1.8中,您檢查"A" ,而不是:A

使用其#class#to_s#inspect可以幫助您了解您定義的對象是否實際上是全局的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM