Tanguy S
Tanguy S

Reputation: 133

Include module , how does it work?

By example :

module Feature
  def self.included(klass)
    puts "#{klass} has included #{self}!"
  end
end

class Container
  include Feature
end

can you explain me how module can manipulate klass ?

can't find any clear documentation about it.

regards.

Upvotes: 3

Views: 2067

Answers (2)

ShallmentMo
ShallmentMo

Reputation: 449

I think include is just a method. This is what I did in irb.

 > require 'pry'
 > module A
 >   def self.included klass
 >     puts "included"
 >   end
 > end
 > class B
 >   binding.pry
 >   include A
 > end

when it enter into pry, I just see this

pry(B)>  self.method(:include)
=> #<Method: Class(Module)#include>

so I think include is a method ,and guess included method is called when include is done. Sorry for this, I don't have any evident on this. Might have to read the ruby source code, because I ask for source_location, but got nil

 pry(B)> self.method(:include).source_location
 => nil

I think ActiveSupport::Concern is used to solve the dependency problem

Upvotes: 2

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

This is a documentation for ActiveSupport::Concern, they make a pretty good job of describing this and a "new" concern approach.

http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

Basically when you include a module, its methods are added as instance methods to the class you include them in. When you extend a module, they become class methods.

So what happens here is when you include Feature the Container gains an included class method which has access to the class itself (using klass). Thanks to this behaviour we can for example include (or extend) dependant modules.

Upvotes: 1

Related Questions