2010-07-23 38 views
9

下面的例子將失敗如何在Ruby中從字符串「A :: B :: C」獲取類對象?

class A 
    class B 
    end 
end 
p Object.const_get 'A' # => A 
p Object.const_get 'A::B' # => NameError: wrong constant name A::B 

UPDATE

關於剛纔問的話題問題:

  1. Cast between String and Classname
  2. Ruby String#to_class
  3. Get a class by name in Ruby?

最後一個gives a nice solution可以演變成

class String 
    def to_class 
    self.split('::').inject(Object) do |mod, class_name| 
     mod.const_get(class_name) 
    end 
    end 
end 

class A 
    class B 
    end 
end 
p "A::B".to_class # => A::B 
+0

'A類開始MY_CONST =「SomeOtherClass」.to_class end'?例如,如果在'initialize'之外調用,我會得到未初始化的常量。 'class_eval',我可以嘗試什麼?謝謝! – Dr1Ku 2011-06-20 22:37:20

回答

7

你必須手動「解析」冒號自己和父模塊/類調用const_get

ruby-1.9.1-p378 > class A 
ruby-1.9.1-p378 ?> class B 
ruby-1.9.1-p378 ?> end 
ruby-1.9.1-p378 ?> end 
=> nil 
ruby-1.9.1-p378 > A.const_get 'B' 
=> A::B 

有人寫了一個qualified_const_get,可能是有趣的。

6

這裏是Rails的constantize方法:

def constantize(camel_cased_word) 
    names = camel_cased_word.split('::') 
    names.shift if names.empty? || names.first.empty? 

    constant = Object 
    names.each do |name| 
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name) 
    end 
    constant 
end 

看到,它開始在Object在這一切之上,然後在雙分號之間使用每個名稱作爲墊腳石去定你想。

相關問題