Enable module, how does it work?

Example:

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

class Container
  include Feature
end

      

Can you explain to me how a module can manipulate a class?

can't find clear documentation about this.

Sincerely.

+3


source to share


2 answers


This is the documentation for ActiveSupport::Concern

, they describe this approach and the "new" approach pretty well.

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



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

So what happens here when you include Feature

is Container

getting a class method included

that has access to the class itself (using klass

). Thanks to this behavior, we can, for example, include (or extend) dependent modules.

+1


source


I believe this 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 he enters pry i just see it

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

      



so I think include is a method and guessing method is included when make is included. Sorry about that, I don't see anything obvious about that. May need to read 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

+2


source







All Articles