Reputation: 365
Given a basic ruby class and module, is there a way to call a method from the module as soon as an instance of the class is extended ?
class Dog
def initialize(name)
@name = name
end
end
module Speech
def say_name
puts @name
end
# call to method in module ?
say_name
end
fido = Dog.new('fido')
fido.extend Speech => *'fido'*
I am aware of the 'included' method that acts sort of like a callback when a module is included, but I was hoping for something similar for extend.
Upvotes: 4
Views: 458
Reputation: 118261
Here is one trick using the method extend_object
.
Extends the specified object by adding this module’s constants and methods (which are added as singleton methods). This is the callback method used by
Object#extend
.
class Dog
def initialize(name)
@name = name
end
end
module Speech
def Speech.extend_object(o)
super
puts o.say_name
end
def say_name
@name
end
end
fido = Dog.new('fido')
fido.extend Speech # 'fido'
Upvotes: 3