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

Google analytics ios screen views

ios google-analytics-api

I've already integrated google analytics SDK v3 in my iOS application and I need now to track the screen views. Here is what I'm currently seeing on their website:

The datetime zone id is not recognised in Jira Atlassian

jira atlassian

I have a problem in Jira (product of Atlassian), when i want to check Agile -> scrum show an alert with this message:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.