2.0.0-p247 :001 > dynamic_name = "ClassName"
=> "ClassName"
2.0.0-p247 :002 > Object.const_set(dynamic_name, Class.new { def method1() 42 end })
=> ClassName
2.0.0-p247 :003 > ClassName.new.method1
=> 42
=> "ClassName"
2.0.0-p247 :002 > Object.const_set(dynamic_name, Class.new { def method1() 42 end })
=> ClassName
2.0.0-p247 :003 > ClassName.new.method1
=> 42
However it might be useful to know that Class.new accepts another class as parameter for making it the class' parent, so if you want to make a dynamic class with inheritence you can do this:
2.0.0-p247 :001 > dynamic_name = "ClassName"
=> "ClassName"
2.0.0-p247 :002 > class A; def method1() 42 end; end
=> nil
2.0.0-p247 :003 >Object.const_set(dynamic_name, Class.new(A) )
=> ClassName
2.0.0-p247 :004 > ClassName.new.method1 #=> 42
=> 42
This is slightly akin to dark magic, try not to use it much or at all... Now excuse me I need to summon some imps.
No comments:
Post a Comment