ruby - Dynamic Class Definition WITH a Class Name -
how dynamically define class in ruby name?
i know how create class dynamically without name using like:
dynamic_class = class.new def method1 end end
but can't specify class name. want create class dynamically with name.
here's example of want of course doesn't work.
(note not creating instance of class class definition)
class testeval def method1 puts "name: #{self.name}" end end class_name = "testeval" dummy = eval("#{class_name}") puts "dummy: #{dummy}" dynamic_name = "testeval2" class_string = """ class #{dynamic_name} def method1 end end """ dummy2 = eval(class_string) puts "dummy2: #{dummy2}" # doesn't work
actual output:
dummy: testeval dummy2:
desired output:
dummy: testeval dummy2: testeval2
======================================================
answer: totally dynamic solution using sepp2k's method
dynamic_name = "testeval2" object.const_set(dynamic_name, class.new) dummy2 = eval("#{dynamic_name}") puts "dummy2: #{dummy2}"
the name of class name of first constant refers it.
i.e. if myclass = class.new
, myclass = myclass
, name of class become myclass
. can't myclass =
if don't know name of class until runtime.
so instead can use module#const_set
, dynamically sets value of const. example:
dynamic_name = "classname" object.const_set(dynamic_name, class.new { def method1() 42 end }) classname.new.method1 #=> 42
Comments
Post a Comment