Re: Global dynamic method definition

From: Philippe L. [mailto:[email protected]]

In 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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs