2012-06-24 149 views
4

在運行時創建類作爲進行中在運行時創建一個類如下:模塊/命名空間

klass = Class.new superclass, &block 
Object.const_set class_name, klass 

例子:

class Person 
    def name 
    "Jon" 
    end 
end 

klass = Class.new Person do 
    def name 
    "#{super} Doe" 
    end 
end 

Object.const_set "Employee", klass 

puts Employee.new.name # prints "Jon Doe" 

現在,讓我們說,你有一個模塊公司名稱:

module Company 
end 

如何創建Employee類公司模塊/名稱空間內的運行時處的s ,以便產生相同的結果?

puts Company::Employee.new.name # prints "Jon Doe" 

回答

12

比你想象:)

Company.const_set "Employee", klass 

當你Object設置一些輕鬆,它成爲全球性,因爲,一切是Object。但是你可以爲每個課程/模塊做const_set。請記住,模塊/類只是常數。所以,Company::Employee是一個常數Employee在常數Company。這很簡單:)

全碼:

class Person 
    def name 
    "Jon" 
    end 
end 

klass = Class.new Person do 
    def name 
    "#{super} Doe" 
    end 
end 

module Company 
end 

Company.const_set "Employee", klass 

Company::Employee.new.name # => "Jon Doe" 
+0

打你2秒字面上:P –

+0

@MichaelKohl:是的,我花了他們在切割/粘貼該行:) –

+0

感謝您的回答和解釋,塞爾吉奧! – danlee

2

您已經有了所有必要的片段:

class Person 
    def name 
    "Jon" 
    end 
end 

klass = Class.new Person do 
    def name 
    "#{super} Doe" 
    end 
end 

module Company 
end 

Company.const_set "Employee", klass 

puts Company::Employee.new.name # prints "Jon Doe" 

Company.constants.grep(/Emp/) 
#=> [:Employee]