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/)