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.

Answers


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.


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


Need Your Help

How to get Anchor Links to work in Jquery Mobile?

javascript jquery jquery-mobile hyperlink

Jquery Mobile has decided to treat anchor links as page requests of sort. However, this isn't good if you have a load of blog posts which have anchor links to the same page (ie href="#specs").