Reputation: 598
I've put some functionality in a module, to be extended by an object. I'd like the functionality to be executed automatically when the module is extended. However, it has to be executed in the context of the instance, not Module.
module X
extend self
@array = [1,2,3]
end
obj.extend(X)
Currently, @array does not get created in the instance. I don't wish to force the developer to call some initialization method, since then for each Module he needs to know the name of a unique method to call. Is this possible ?
Upvotes: 7
Views: 3354
Reputation: 12225
You can use Module#extended hook for execution code on extension and BasicObject#instance_exec (or BasicObject#instance_eval) for executing arbitrary code in context of extended object:
module X
def self.extended(obj)
obj.instance_exec { @array = [1,2,3] }
end
end
class O
attr_reader :array
end
obj = O.new
obj.array # => nil
obj.extend(X)
obj.array # => [1, 2, 3]
Upvotes: 11