Ruby modules: include/extend
This course covers Ruby's module keyword and the two ways to attach a module's methods to a class. It starts with module/end and why a module has no .new method. The include keyword inserts the module into a class's ancestors, so every instance gets its methods. The extend keyword works through the singleton class, so the class itself gets them. Later lessons compare both on one module, show modules as namespaces, examine the app's Translatable concern and combine both through the self.included hook.
What you'll learn
- ✓Defining a module with module/end and why it cannot be instantiated
- ✓Using include to add instance methods through the ancestors chain
- ✓Using extend to add class methods through the singleton class
- ✓Choosing between include and extend, and recognizing the self.included hook
- ✓Using modules as namespaces to group related classes
- ✓Reading the app's Translatable mixin and its locale fallback
What a module is
The two previous Ruby OOP courses used class/end to build blueprints and def/end to build methods. Ruby has a third container, module/end. It looks almost like a class but does a different job:
Read the full lesson free →Curriculum
7 lessonsWhat a module is
Introduces module/end as a container of methods and shows that calling .new on a module raises NoMethodError.
include adds instance methods
Shows how include inserts a module into a class's ancestors so every instance can call its methods.
extend adds class methods
Shows how extend puts a module's methods on the class itself through its singleton class, leaving instances without them.
include vs extend, same module
Compares include and extend on one module and introduces the self.included hook that triggers both.
Modules as namespaces
Explains modules used only as namespaces, like Catalog::Course, to group classes and prevent name collisions.
A real mixin: Translatable
Examines the app's Translatable concern, its generated title methods, English fallback and ClassMethods added through ActiveSupport::Concern.
Putting it together: both mechanisms, one class
Builds an Auditable module whose single include gives Invoice an instance method and two class methods.