Include and Extend: Understanding Ruby on Rails Module Inclusion
A Deep Dive into the include
and extend
Methods
In Ruby on Rails, include
and extend
are used to add the functionality of a module to a class or an instance of a class. Both methods serve different purposes and are used in different scenarios. Here, we'll explain the differences between the two and provide examples to illustrate their usage.
Include
include
: When a module is included in a class using include
, the module's instance methods become available as instance methods of the class. This means that the module methods can be called on instances of the class, rather than the class itself.
Example:
In the example above, the Greetable
module is included in the Person
class. The greet
method from the module is now available as an instance method on Person
, so it can be called on an instance of Person
.
Extend
extend
: When a module is extended in a class using extend
, the module's instance methods become available as class methods of the class. This means that the module methods can be called on the class itself, rather than instances of the class.
In the example above, the Greetable
module is extended in the Person
class. The greet
method from the module is now available as a class method on Person
, so it can be called on the Person
class itself.
In summary, the main difference between include
and extend
is how the module methods are added to the class. include
adds the module's methods as instance methods of the class, while extend
adds the module's methods as class methods of the class.