This is useful if you are trying to create class methods metaprogramatically:
def self.create_methods(method_name)
# To create instance methods:
define_method method_name do
...
end
# To create class methods that refer to the args on create_methods:
???
end
My answer to follow...
To be used in Rails if you want to define class methods dynamically from concern:
This is the simplest way in Ruby 1.8+:
I prefer using send to call define_method, and I also like to create a metaclass method to access the metaclass:
Derived from: Jay and Why, who also provide ways to make this prettier.
Update: from VR's contribution below; a more concise method (as long as you're only defining one method this way) that is still standalone:
but note that using send() to access private methods like define_method() is not necessarily a good idea (my understanding is that it is going away in Ruby 1.9).
I think in Ruby 1.9 you can do this:
You could also do something like this without relying on define_method: