Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 134 ยท Object-Oriented Ruby

Modules and Mixins

Learn Ruby modules - namespaces, mixins with include, extend and prepend, ancestors and method lookup, module constants, module_function and when to choose a module over a class.

A class in Ruby can have only one superclass, yet real programs need to share behavior across unrelated classes: "can be compared", "can be iterated", "can be logged". Ruby solves this with modules. A module is a named bundle of methods and constants that is not a class: you cannot create an instance of it and it cannot be subclassed. Instead you mix it into classes, and its methods become part of those classes.

A module has two jobs, and it helps to keep them apart in your mind. First, it is a namespace: a named container that stops your Parser class from colliding with someone else's Parser. Second, it is a mixin: reusable behavior you add to a class with include, extend or prepend. This lesson covers both, shows exactly how Ruby decides which method wins (the ancestors list), and gives you rules for choosing between a module and a class.

A module is not a class

Ruby What a module can and cannot do (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first three lines print Module, true and Module: a Class is a special kind of Module, which is why every class can also hold constants and methods. The last line ends with main.rb:8:in '<main>': undefined method 'new' for module Greeting (NoMethodError), followed by the source line with a caret under new. A module has no new, because it describes behavior, not a thing you can build.

Modules as namespaces

The simplest use of a module is to group constants, classes and helper methods under one name. You reach inside with the :: operator.

Ruby Namespaces with module and ::

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

There are two different Circle classes and no conflict, because their full names are Geometry::Circle and Graphics::Circle. The method def self.describe lives on the module object itself, so you call it as Geometry.describe(...). Namespaces nest as deeply as you like (Billing::Invoices::Line), and libraries put everything inside one top-level module for exactly this reason.

module A::B (compact style) and module A; module B (nested style) both define A::B, but they differ in constant lookup. Inside the compact form, constants of A are not automatically visible. Prefer the nested form when the inner code needs the outer constants.

include: instance methods from a module

include adds a module's methods to the instances of a class. The module is inserted into the class's chain of ancestors, right after the class itself.

Ruby include and ancestors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Both modules define move. The output of d.move is Donald swims, because the module included last sits closest to the class in the ancestors list, so it is searched first. Duck.ancestors.first(4) prints [Duck, Swimmable, Walkable, Animal]. This list is the whole story of method lookup: Ruby walks it left to right and runs the first method it finds. A module also counts for type checks: d.is_a?(Swimmable) is true, which is how Ruby expresses "this object can do that" without inheritance.

The mixin pattern: write one method, get many

The most famous mixins ask you to implement one method and give you a whole API in return. Comparable needs <=>, and Enumerable needs each. You can write your own in the same style.

Ruby A mixin that needs one method from its host

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The mixin calls label and summary without defining them, and each host class supplies them. This is the template method idea expressed with a module. The last line fails with main.rb:2:in 'Describable#describe': undefined local variable or method 'label' for an instance of Broken (NameError) (the trace then adds from main.rb:35:in '<main>'), which shows the contract: if you include a module, you must provide the methods it relies on. Document that contract in a comment at the top of the module.

extend: module methods as class methods

include is for instances. extend adds the module's methods to one particular object, and when that object is a class, they become class methods.

Ruby extend on a class and on a single object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ticket.instances_created prints 3. extend Countable is shorthand for "include the module into the singleton class of this object", which is the hidden class each Ruby object can have for its own personal methods (Singleton Methods and the Singleton Class explains it). That is why label can speak but a different string cannot.

A common idiom combines both: a module offers instance methods and also class-level macros through the included hook, which Ruby calls when the module is included.

Ruby The included hook adds class methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

One include line gives instances valid? and gives the class the required macro. You will see this shape in many libraries, and Hooks and Callbacks covers the callbacks in detail.

prepend: go in front of the class

include puts a module behind the class in the ancestors list, so the class's own methods win. prepend puts the module in front, so the module's version runs first and can call the class's version with super. That makes it the clean way to wrap behavior.

Ruby include versus prepend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Plain.new.save prints no "before/after" lines at all: Plain defines its own save, which sits ahead of Logging in the chain ([Plain, Logging, Object]), so the module's version is never reached. With Wrapped, the ancestors list begins [Logging, Wrapped, Object], so Logging#save runs first, calls super to reach the class's own save, and wraps it. Prepending is the modern replacement for the old alias_method chain trick and is the safest way to add behavior around an existing method (Monkey Patching and Safe Alternatives).

Method lookup in one picture

The rule is short: for a call on an object, Ruby searches the object's singleton class, then each entry of obj.class.ancestors in order, and runs the first match. The order for a class is: prepended modules (last prepended first), the class itself, included modules (last included first), then the superclass and the same pattern again, up to Object, Kernel and BasicObject.

Ruby Reading a full ancestors chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints [C, Child, D, B, Base, A, Object]: the prepended C first, then Child, then the included modules with the latest (D) before B, then the superclass Base followed by its own module A. Note that Kernel and BasicObject come after Object. The last line prints Kernel, because to_s is inherited from there.

What if the same module is included twice, or by both parent and child? Ruby ignores the second inclusion if the module already appears in the chain. That prevents loops and duplicate work.

Calling super through mixins

Because every module sits in the chain, super simply means "the next one along". Cooperative mixins can each add a piece and pass control on.

Ruby A chain of modules cooperating with super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The result is "hello world". Lowercased runs first (included last), lowercases, and hands the text to Trimmed, which strips and passes it to Pipeline#clean. Reorder the two include lines and the order of work changes. If a module calls super and no later method exists, Ruby raises NoMethodError (super: no superclass method 'clean'), so cooperative modules usually sit on top of a base class that defines the method.

Module constants and module_function

Modules can hold constants, which is how Math::PI and File::SEPARATOR work. Constants are found through the lexical scope first, then through the ancestors of the enclosing class.

A module can also be a toolbox of plain functions, like Math. There are two ways to build one. The explicit way is def self.name. The shortcut is module_function, which makes the method callable on the module and keeps a private copy for classes that include it.

Ruby module_function and extend self

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Temperature.to_fahrenheit(100) prints 212.0. Inside Thermostat, the included copy is private, so report can call it but the last line fails with main.rb:26:in '<main>': private method 'to_fahrenheit' called for an instance of Thermostat (NoMethodError). extend self is the alternative: the module extends itself, so its instance methods double as module methods and stay public for includers. Choose module_function for pure utilities and extend self when you want both uses to stay public.

Module or class?

Ask: "Do I need to create objects of this?" If yes, it is a class. If it is a place to put shared behavior or related constants, it is a module.

  • Use a class when you have state per object and want new.
  • Use a module as a namespace to group related classes and avoid name clashes.
  • Use a mixin for behavior shared by classes that are not in the same family: a role or capability (Comparable, Enumerable, Loggable). Prefer small modules that do one thing.
  • Use module_function for stateless helpers.
  • Avoid mixins that quietly depend on many instance variables of the host. They are hard to read and hard to test. When a module needs lots of the host's internals, a separate collaborator object (composition) is usually a better design (Duck Typing and Polymorphism, Design Principles in Ruby).

A final pitfall: a module is global once defined, and a mixin affects every class that includes it. Adding a method to a widely used module (or to Kernel) changes the whole program, so keep your changes local.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about modules is true?

    A module cannot be instantiated or subclassed. It serves as a namespace and as a mixin that classes include, extend or prepend.
  2. 2. A class includes module A and then module B, and both define hello. Which one wins for an instance?

    Each include inserts the module directly behind the class, so the latest include comes first in ancestors and is found first.
  3. 3. What does extend do when called inside a class body?

    extend mixes the module into the singleton class of the receiver. For a class, that means its methods become class methods.
  4. 4. Why use prepend instead of include to wrap an existing method with logging?

    With include, the class's own method comes first and the module's version is never reached. prepend reverses that.
  5. 5. What happens to a method defined with module_function when a class includes the module?

    module_function makes a public module-level copy and a private instance-level copy, so including classes can call it internally but not from outside.

Summary

  • A module is a named bundle of methods and constants; it cannot be instantiated or subclassed.
  • As a namespace, a module prevents name clashes (Geometry::Circle).
  • include adds instance methods, extend adds methods to one object or to a class, and prepend places the module before the class so it can wrap methods with super.
  • ancestors shows the exact lookup order; the latest include comes first, prepended modules come before the class.
  • The included hook lets one include line add class-level macros too.
  • module_function and extend self build utility modules.
  • Prefer small, single-purpose mixins; reach for composition when a mixin depends on too much of its host.

Next: public, private and protected