I would like to solve a problem where a writer of a class can provide an
array of fields and those fields are turned into two things.
-
A method called #each_“field_name” that iterates over all of the
values in that field. -
A method called #each_combination that defines a series of nested
called to #each_“field_name” and at the inside yields a combination of
the parameters.
I have the code to solve #1. That was a pretty straight-forward
exercise. See the code below (save it to a file and run it).
module Parameters
module Base
def self.create_each(mod, fields)
fields.each do |field_name|
code = <<-code
def each_#{field_name}
@params[’#{field_name}’].each do |value|
@#{field_name}_current_value = value
yield(value)
end
end
code
p code
mod.class_eval(code)
end
end
end # Base
end # Parameters
if FILE == $0
class Test
include Parameters::Base
def self.fields
['dollars', 'activation_time', 'personnel_count']
end
Parameters::Base.create_each(self, fields)
def initialize
@params = {
'dollars' => [1_000, 5_000, 75_000],
'activation_time' => ["06:30", "08:00", "10:00"],
'personnel_count' => [1, 3, 7, 25]
}
end
end
end
I’m stuck on solving #2. I want to nest each call to #each_‘field_name’
in the order given in the #fields class method. The innermost call
should yield each of the block parameters.
Given the details above, I would like to produce a method like this:
def each_combination(&blk)
each_dollars do |dollars|
each_activation_time do |activation_time|
each_personnel_count do |personnel_count|
yield(dollars, activation_time, personnel_count)
end
end
end
end
Any hints on how I can accomplish #2 here? I tried a few approaches
similar to my #create_each metaprogramming, but I can’t get the syntax
right.
cr