Re: Global dynamic method definition

I’m trying to code in Ruby something that looks like this,
when reduced and highly simplified:
[snip]
As the code suggest, what I except is:

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

Depending on how much you’ve simplified it, you might see if the
following code helps. (I wonder if you really need to dynamically define
a new method; you certainly don’t to achieve the desired output of your
sample.)

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
end

def dynamic_method
self.class.dynamic_method_outputs.each do |v|
puts v
end
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