Global dynamic method definition

Hi,

I’m trying to code in Ruby something that looks like this, when reduced
and highly simplified:


class B
puts “B class init”
@@dynamic_method_outputs = Array.new

def initialize
puts “B instance init”
end

def B.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

The output of this is:

B class init
B instance init
123
456
B instance init
123
456
789

As the code suggest, what I except is:

B class init
B instance init
123
456
B instance init
789

In other words, the global @@dynamic_method_outputs is not cleared
between D1 and D2 class definitions.

The only trick I could find for the moment is to use a dummy
instanciation, but it is still not really clean, and prone to errors.


class B
puts “B class init”
@@dynamic_method_outputs = Array.new

def initialize
puts “B instance init”
@@dynamic_method_outputs.clear
end

def B.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
D1.new

class D2 < B
add_to_dynamic_method_output 789
end
D2.new

d1 = D1.new
d1.dynamic_method

d2 = D2.new
d2.dynamic_method
789

Output is here:

B class init
B instance init
B instance init
B instance init
123
456
B instance init
789

Does anyone have a better idea?

Philippe

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