3

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.

Tanguy S
  • 133
  • 1
  • 14
  • What is exactly unclear to you? – Marek Lipka May 07 '15 at 11:15
  • how klass is transmitted to the module ? wath does 'included' method ? – Tanguy S May 07 '15 at 11:17
  • 1
    Probably [this](http://stackoverflow.com/questions/151505/difference-between-a-class-and-a-module) reference may help. – Saubar May 07 '15 at 11:17
  • 1
    In the below link a good explanation of hook methods: `included`, `extended`, `prepended`, `inherited`, `method_missing` http://www.sitepoint.com/rubys-important-hook-methods – Talgat Medetbekov May 07 '15 at 11:21
  • i didn't ... admin's action i think . your link was really usefull , but maybe not enough to be an answer , but enough to be a great comment.anyway thank you – Tanguy S May 07 '15 at 14:00

2 Answers2

2

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

ShallmentMo
  • 449
  • 1
  • 4
  • 15
1

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.

Piotr Kruczek
  • 2,384
  • 11
  • 18