I want to create a class method that takes a block of method definitions and injects it into the class. Now, self
is indeed the Tom
object so class << self
does open it up, but yield
doesn't seem to work. My theoretical knowledge is not that deep, so I am not sure why this is not working. I might be getting this totally wrong, so feel free to discuss alternatives.
class Tom < Person
mega_methods do
def hiya!
puts 'hiYA!'
end
end
end
class Person
def self.mega_methods
...
class << self
yield
end
end
end
Tom.hiya!
I am aware I could just define the methods in Tom
using class << self
or that I could include class << self
in the block.
I also figured out this alternative:
def self.mega_methods &block
if block_given?
extension = Module.new(&Proc.new)
self.extend(extension)
end
end
This question is more about helping me understand the workings of Ruby rather than solving a specific issue.