As the code suggest, what I except is:
B class init
B instance init
123
456
B instance init
789In other words, the global @@dynamic_method_outputs is not
cleared between D1 and D2 class definitions.
Class variables are shared between a class and all its subclasses. You
want an instance variable of the class itself:
class B
puts "B class init"
def self.dynamic_method_outputs
@dynamic_method_outputs ||=
end
def initialize
puts "B instance init"
end
def self.add_to_dynamic_method_output(val)
dynamic_method_outputs << val
method_def = "def dynamic_method() "
dynamic_method_outputs.each do |v|
method_def << "puts #{v} \n"
end
method_def << "end"
self.class_eval method_def
end
end
class D1 < B
add_to_dynamic_method_output 123
add_to_dynamic_method_output 456
end
class D2 < B
add_to_dynamic_method_output 789
end
d1 = D1.new
d1.dynamic_method
d2 = D2.new
d2.dynamic_method
#=> B class init
#=> B instance init
#=> 123
#=> 456
#=> B instance init
#=> 789
···
From: Philippe Lang [mailto:philippe.lang@attiksystem.ch]