Modules and mixins
A module is a container for methods and constants that isn't a class: you can't create objects from it. Modules do two jobs in Ruby: they group related code under a name (a namespace), and they share behaviour between classes as mixins. Mixins are how Ruby gets the benefits of multiple inheritance without its problems.
Modules as namespaces
Math::PI and JSON.parse work exactly like this: Math and JSON are modules. Namespaces stop names from clashing: your Geometry::Point and a library's Graphics::Point can live side by side.
Modules as mixins: include
include adds a module's methods to a class as instance methods. Any number of classes can share them:
The module expects the class to provide name. That's the typical mixin contract: "include me and give me X, and I'll give you Y". Ruby's own Comparable (needs <=>) and Enumerable (needs each) are mixins of exactly this kind.
Method lookup
When you call a method, Ruby searches the object's class, then the modules it includes (last included first), then the superclass, and so on. ancestors shows the order:
- With
include, the class's own method wins, andsuperreaches the module. - With
prepend, the module's method runs first and can wrap the class's method withsuper, which is great for adding logging, caching or timing around existing methods.
extend: class-level methods
extend adds a module's methods to a single object, most often to a class itself (as class methods):
That's a tiny version of how ActiveRecord (Rails) gives every model create, all and find_by.
included hook: both at once
A common pattern adds instance methods and class methods with one include:
Module functions and constants
Utility modules often expose methods that can be called on the module directly:
freeze makes an object unchangeable, so a constant really stays constant.
Refinements, briefly
Ruby lets you reopen any class, even String, and add methods ("monkey patching"). It's powerful but risky, because the change affects the whole program. Refinements limit such changes to the files that ask for them:
Practice
- Write a
Timestampsmodule withtouch(sets@updated_at = Time.now) and include it in two classes. - Write a
Countablemodule that, when included, gives the class acountclass method tracking how many objects were created. - Use
prependto add logging around an existingsavemethod. - Organise three related classes inside a
Shopnamespace module.
1.What does include MyModule do in a class?
2.How is extend different from include?
3.What does prepend let a module do?
4.What must a class provide to include Comparable?