Wednesday 8 October 2014

Dynamic Class definition with inheritance in Ruby

If for some reason you need to have a class Dynamically defined in Ruby the following code will do you fine:

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

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.