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 ?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With