30
loading...
This website collects cookies to deliver better user experience
include
, extend
and prepend
work in ruby.include
or extend
the module.include
and extend
? When a class include
's a module, it adds the module methods as instance methods on the class.extend
's a module, it adds the module methods as class methods on the class.module A
def hello
"world"
end
end
class Foo
include A
end
class Bar
extend A
end
Foo.new.hello #works
Foo.hello #error
Bar.new.hello #error
Bar.hello #works
self.included
callback. Whenever a class includes a module, it runs the self.included
callback on the module. We can add the logic for extending another module on the class inside of the self.included
method.module A
def self.included(base)
base.extend(ClassMethods)
end
def hello
"world"
end
module ClassMethods
def hi
"bye"
end
end
end
class Foo
include A
end
Foo.new.hello #works
Foo.hello #error
Foo.new.hi #error
Foo.hi #works
self.included
, lets us provide both instance and class methods when the module is included.extend
the module in this example, then Foo would have hello
as a class method but not hi
.module A
def self.included(base)
base.extend(ClassMethods)
end
def hello
"world"
end
module ClassMethods
def hi
"bye"
end
end
end
class Foo
extend A
end
Foo.new.hello #error
Foo.hello #works
Foo.new.hi #error
Foo.hi #error
module A
def hello
"world"
end
end
class Foo
include A
end
Foo.ancestors # [Foo, A, Object, Kernel, BasicObject]
module A
def hello
"world"
end
end
class Bar
extend A
end
Bar.ancestors # [Bar, Object, Kernel, BasicObject]
Bar.singleton_class.ancestors # [#<Class:Bar>, A, #<Class:Object>, #<Class:BasicObject>, Class, Module, Object, Kernel, BasicObject]
include
in its functionality. The only difference is where in the ancestor chain the module is added. With include
, the module is added after the class in the ancestor chain. With prepend, the module is added before the class in the ancestor chain. This means ruby will look at the module to see if an instance method is defined before checking if it is defined in the class.Module A
def hello
put "Log hello in module"
super
end
end
class Foo
include A
def hello
"World"
end
end
Foo.new.hello
# log hello from module
# World