2010-02-22 52 views

回答

6

如果您事先知道需要定义哪些类,则可能应该生成明确定义它们的代码,以便清楚地说明关键字class

但是,如果您确实需要动态定义它们,则可以将Object.const_setClass.new结合使用。要定义的ActiveRecord::Base几个子类:

%w{A B C D}.each do |name| 
    Object.const_set name, Class.new(ActiveRecord::Base) 
end 

上述结果为四个名为A..D新班,ActiveRecord::Base所有儿童。

+0

哇,真好!非常感谢 – marshluca 2010-02-23 04:21:09

5

在文本编辑器中使用宏或脚本可能会更好。以编程方式创建类使他们难以记录。

+0

+1,以支持运行时生成的代码生成。后者有时是做某事的唯一方式,但通常不是最好的方式。 – OregonGhost 2010-02-22 10:19:00

+0

+1为清晰度超过聪明。 – 2011-09-14 16:43:16

3

您可以定义类完全动态:

A = Class.new(ActiveRecord::Base) do 
    # this block is evaluated in the new class' context, so you can: 
    # - call class methods like #has_many 
    # - define methods using #define_method 
end 
0

我觉得“元编程红宝石”对如何避免使用class关键字测验问题,但我不知道这会帮助你解决你的问题。

相关问题