[ruby 1.8]
Assume I have:
dummy "string" do
puts "thing"
end
Now, this is a call to a method which has as input arguments one string and one block. Nice.
Now assume I can have a lot of similar calls (different method names, same arguments). Example:
otherdummy "string" do
puts "thing"
end
Now because they do the same thing, and they can be hundreds, I don't want create an instance method for each one in the wanted class. I would like rather find a smart way to define the method dynamically at runtime based on a general rule.
Is that possible? Which techniques are commonly used?
Thanks
I'm particularly fond of using
method_missing
, especially when the code you want to use is very similar across the various method calls. Here's an example from this site - whenever somebody callsx.boo
andboo
doesn't exist, method_missing is called withboo
, the arguments toboo
, and (optionally) a block:define_method
also looks like it would work for you, but I have less experience with it thanmethod_missing
. Here's the example from the same link:use define_method:
Output:
Yes, there are a few options.
The first is
method_missing
. Its first argument is a symbol which is the method that was called, and the remaining arguments are the arguments that were used.The other option is dynamically creating the instance methods at runtime, if you know in advance which methods will be needed. This should be done in the class, and one example is like this:
It is a common pattern to have
define_method
called in a class method which needs to create new instance methods at runtime.