Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: can module execute initialization code automatically?

Tags:

ruby

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 ?

like image 678
rahul Avatar asked Dec 28 '11 07:12

rahul


1 Answers

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]
like image 59
Victor Deryagin Avatar answered Nov 06 '22 07:11

Victor Deryagin