tags:

views:

459

answers:

3

I'm looking at a module X which contains two modules called "InstanceMethods" and "ClassMethods".

The last definition in module X is this:

  def self.included(base)
    base.send :include, InstanceMethods
    base.send :extend,  ClassMethods
  end

What does this do?

A: 

It's defining a class method which takes a parameter "base". It then calls the include and extend methods on base, passing the module InstanceMethods and ClassMethods as arguments, respectively. The call to include will add the instance methods defined in InstanceMethods to base. I'm not familiar with the extend method, but I assume it will do something like that too, but for class methods.

dylanfm
A: 

'send' invokes its first argument as a method on the object its called on, and the rest of the arguments are sent as arguments to the method. So in this case,

base.send :include, InstanceMethods

is equivalent to

base.include(InstanceMethods)

Which adds the methods in the InstanceMethods module to the 'base' object

cloudhead
It's not quite equivalent, as `base.send :include` will still call include even if the method has been made private. `base.include` will raise an error.
Oliver N.
+4  A: 

included gets called whenever a module is included into another module or class. In this case it will try to invoke base's include method to get the module methods, variables and constants from InstanceMethods added into base and then will try to invoke base's extend method to get the instance methods from ClassMethods added to base.

It could also have been

def self.included( base )
  base.include( InstanceMethods )
  base.extend( ClassMethods )
end
toholio
Ok, that makes sense. There's a class W that is including module X, so the idea is that W gets all of the instance methods and class methods contained in X through these modules. The missing piece was how 'included' gets called - but you're saying as soon as I say "W include X", the included() method will be called. – franz 0 secs ago
franz
That's right. There's some more information and a friendly example at http://ruby-doc.org/core/classes/Module.html#M001683
toholio