Don't understand include/extend module mixupe

Example of code with text before:

A Common Idiom

Even though include is for adding instance methods, a common idiom
you’ll see in Ruby is to use include to append both class and instance
methods. The reason for this is that include has a self.included hook
you can use to modify the class that is including a module and, to my
knowledge, extend does not have a hook. It’s highly debatable, but often
used so I figured I would mention it. Let’s look at an example.

module Foo
def self.included(base)
base.extend(ClassMethods)
end

module ClassMethods
def bar
puts ‘class method’
end
end

def foo
puts ‘instance method’
end
end

class Baz
include Foo
end

Baz.bar # class method
Baz.new.foo # instance method
Baz.foo # NoMethodError: undefined method ‘foo’ for Baz:Class
Baz.new.bar # NoMethodError: undefined method ‘bar’ for #Baz:0x1e3d4

I don’t understand

def self.included(base)
base.extend(ClassMethods)
end

this is url
http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/)

At the point of

include Foo

the method Foo::included is called. The formal parameter of this method
(base) receives as actual parameter the class object of the including
class, Baz. With other words: base is Baz in this case.

Baz, being a class object, has a method “extend”, which is invoked here.
Extend expects as its parameter a Module object, and in this case it
receives the Module “ClassMethods”.

The method “extend” then takes every instance method of the module being
passed as argument (in this case, there is only one: “bar”) and includes
it in the class, “Baz”, as a class method.

Hence, “bar” becomes a class method of “Baz”.

Thank you. You made it so clear

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs