7

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 ?

2 Answers 2

11

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to both Victor and avy.
4

Show this article

module Math
  def self.extended(base)
    # Initialize module.
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.