Thuta Learning
Ruby
AdvancedProgrammingBeginner

Modules & Mixins

RubyLesson 2130 min

What you'll walk away with

  • Use a module as a namespace so two classes with the same name never collide
  • Say where include, extend and prepend each place a module
  • Read Class.ancestors to predict the order of modules
  • Define <=> and include Comparable to get comparisons, sort and clamp
  • Build a utility module with module_function

Explain it simply

Modules in plain language

Picture a module as a labelled basket of methods and constants. Unlike a class it cannot create objects, but it does two jobs. The first is a namespace: it groups names so they cannot collide. The second is a mixin: it hands a shared behaviour to classes that have nothing else in common.

A class can have only one parent, but you can add as many modules as you like. That is how a Dog can inherit from Animal and also pick up Runner and Swimmer. You choose which baskets to put into your class, so no code is written twice.

Problem → Why → Solution

The problem: two classes with one name wreck each other

An online shop has an Item class that calculates prices. Later someone adds a game system and names its class Item as well. In Ruby, writing class Item a second time does not create a new class; it reopens the existing one, so the second initialize replaces the first.

The trouble is that the error appears on the price line, far from where the names collided, and Ruby gives no warning at all. The more files use Item, the harder it becomes to find who changed what. Putting each class inside a module namespace avoids the problem completely.

item_clash.rb
class Item                         # the shop's item
  def initialize(price)
    @price = price
  end

  def total = @price * 1.2
end

class Item                         # a game's item: this REOPENS the same class
  def initialize(power)
    @power = power
  end
end

puts Item.new(5).total             # NoMethodError: undefined method '*' for nil

A namespace gives each name its own address

With Shop::Item and Game::Item the names are longer, but the two classes are completely separate. A module wraps the constants, classes and methods inside it, and you reach them with ::, so collisions cannot happen. As a mixin, a module goes into many different classes and reuses code across them.

Core concept: namespaces and mixins

A module is a named bundle of methods and constants. Unlike a class it can never be instantiated: Swimmer.new raises NoMethodError, and nothing can inherit from it. Class is in fact a subclass of Module, so a class is a module that can also create objects. Modules do two different jobs in Ruby, and it helps to keep them apart: namespacing and mixing in behaviour.

As a namespace, a module wraps names so they cannot collide. Shop::Item and Game::Item are two unrelated classes, reached with the :: operator, and constants such as Shop::TAX can live inside the namespace as well. Methods defined with def self.name on a module are called on the module itself, as in Shop.version. Without namespaces, a second class Item in the same program reopens the first one and silently changes it, as the problem above showed.

As a mixin, a module shares instance methods with classes that are not related by inheritance. include Swimmer inserts the module into the class's ancestor chain just above the class itself, so Dog.ancestors becomes [Dog, Swimmer, Runner, Animal, ...]. When two modules are included, the one included last sits closer to the class and is searched first. A method in the class overrides one from a module, and super inside it reaches the module's version, which is how the module and the class cooperate.

Three keywords place a module differently. include puts it behind the class, so instances get its methods and the class's own methods win. prepend puts it in front of the class, so the module's method runs first and can wrap the class's version by calling super. extend adds the module's methods to one single object, and when you extend a class itself they become class methods. A mixin has no state of its own; its methods use whatever readers and instance variables the including object provides, like name above, so document what a mixin expects from its host.

KeywordWhere the module goesMethods become
includeBehind the class in ancestorsInstance methods
prependIn front of the class in ancestorsInstance methods that run before the class's own
extendThe object's singleton classMethods of that one object (class methods inside a class body)
Mental model: a labelled basket
  1. A module is a named bag of methods
  2. include puts the bag behind the class
  3. prepend puts it in front of the class
  4. extend hands it to one object or class

Lookup moves left to right through ancestors, so where you put the module decides which method wins.

General pattern

ruby
module Namespace
  CONSTANT = 1
  def self.helper = "called on the module"   # Namespace.helper
  def shared = "mixed in"                    # instance method for hosts
  class Inner; end                           # Namespace::Inner
end

class Host
  include Namespace      # instance methods, after Host in ancestors
  extend Namespace       # class methods
  prepend Namespace      # instance methods that run before Host's own
end

A module can hold constants, def self.methods, ordinary instance methods and classes. The Host class picks whichever of include, extend and prepend it needs; using all three at once here is only for illustration.

Example: giving Dog and Fish the Runner and Swimmer mixins

Swimmer and Runner are mixins, and Animal is an ordinary parent class. Dog gets both abilities and Fish only swimming, and neither needs a special parent. Look at how Dog.ancestors lists the modules between Dog and Animal, with the one included last placed first.

The error line in the output is the Ruby 4.0.9 wording. From Ruby 3.4 on, the name inside an undefined method message is wrapped in plain apostrophes, while older versions pair a backtick with an apostrophe.

mixins.rb
module Swimmer
  def swim
    "#{name} swims"
  end
end

module Runner
  def run
    "#{name} runs"
  end
end

class Animal
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

class Dog < Animal
  include Runner
  include Swimmer
end

class Fish < Animal
  include Swimmer
end

dog = Dog.new("Rex")
fish = Fish.new("Nemo")

puts dog.run
puts dog.swim
puts fish.swim
puts fish.respond_to?(:run)
p Dog.ancestors
puts dog.is_a?(Swimmer)

begin
  Swimmer.new
rescue NoMethodError => e
  puts e.message
end

Code breakdown

  1. Module body"#{name} swims"

    swim in Swimmer calls name, but the module defines no name. This mixin therefore expects whichever class includes it to supply one.

  2. Include orderinclude Runner

    Dog includes Runner first and Swimmer second. Swimmer, included last, sits closer to Dog in ancestors, so it is searched first when method names clash.

  3. Opt-in per classputs fish.respond_to?(:run)

    Fish never included Runner, so the answer is false. Each class opts in to the abilities it wants.

  4. The ancestors chainp Dog.ancestors

    It prints [Dog, Swimmer, Runner, Animal, Object, Kernel, BasicObject]. You can see each module sitting as a real step in the chain.

  5. Modules count for is_a?puts dog.is_a?(Swimmer)

    is_a? returns true for an included module, so you can ask "can it swim?" through the module instead of checking class by class.

  6. Modules are not classesSwimmer.new

    A module has no new method, so you get NoMethodError, "undefined method 'new' for module Swimmer". A module is a basket, not a factory.

You should see
Rex runs
Rex swims
Nemo swims
false
[Dog, Swimmer, Runner, Animal, Object, Kernel, BasicObject]
true
undefined method 'new' for module Swimmer

Namespaces and module_function utilities

The code below fixes the problem with a namespace: Shop::Item and a top-level Item can live side by side and each follows its own rules. The constant TAX can be used plainly inside Shop::Item because lookup checks the enclosing module. For utility modules, module_function is the tool: the methods below it can be called on the module itself, as in MathUtil.square(4), and when a class includes the module it also gets a private instance copy, so square(3) works inside the class but calculator.square(2) from outside raises NoMethodError.

namespace_and_utils.rb
module Shop
  TAX = 0.2

  class Item
    def initialize(price)
      @price = price
    end

    def total = (@price * (1 + TAX)).round(2)
  end

  module Util
    def self.money(amount) = format("$%.2f", amount)
  end

  def self.version = "1.0"
end

class Item                  # a different, top-level Item
  def total = 0
end

puts Shop::Item.new(10).total      # 12.0
puts Item.new.total                # 0
puts Shop::Util.money(3)           # $3.00
puts Shop.version                  # 1.0
puts Shop::TAX                     # 0.2
p Shop::Item.name                  # "Shop::Item"
p Shop.constants.sort              # [:Item, :TAX, :Util]

module MathUtil
  module_function

  def square(x) = x * x
  def cube(x) = x * x * x
end

puts MathUtil.square(4)            # 16

class Calculator
  include MathUtil

  def run = square(3)              # the instance copy is private
end

puts Calculator.new.run            # 9
begin
  Calculator.new.square(2)
rescue NoMethodError => e
  puts e.message                   # private method 'square' called for ... Calculator
end

include, extend and prepend side by side

Prepend Loud and include Polite in Dog. The chain is [Loud, Dog, Polite, Animal], so calling speak runs Loud first, then super reaches Dog, then Polite and Animal in turn. The result is "WOOF PLEASE, HELLO!". prepend suits decorating work, where you wrap an existing method without editing it.

text
Where each keyword puts the module
----------------------------------
  prepend Loud                               include Polite
       |                                           |
       v                                           v
  [ Loud ] -> [ Dog ] -> [ Polite ] -> [ Animal ] -> [ Object ] -> ...
  runs first   the class   searched after the class
include_extend_prepend.rb
module Loud
  def speak = super.upcase + "!"
end

module Polite
  def speak = "please, " + super
end

class Animal
  def speak = "hello"
end

class Dog < Animal
  prepend Loud
  include Polite

  def speak = "woof " + super
end

puts Dog.new.speak               # WOOF PLEASE, HELLO!
p Dog.ancestors.first(4)         # [Loud, Dog, Polite, Animal]

module Greeter
  def hi = "hi from #{self.class}"
end

class Foo
  extend Greeter                 # becomes Foo.hi
  include Greeter                # becomes Foo.new.hi
end

puts Foo.hi                      # hi from Class
puts Foo.new.hi                  # hi from Foo

module Trackable
  def self.included(base)
    base.extend(ClassMethods)    # runs when a class says include Trackable
  end

  module ClassMethods
    def registry = @registry ||= []
  end

  def register = self.class.registry << name
end

class Plugin
  include Trackable
  attr_reader :name

  def initialize(name) = @name = name
end

Plugin.new("a").register
Plugin.new("b").register
p Plugin.registry                # ["a", "b"]

Trackable shows a common idiom: when a class includes it, Ruby calls self.included(base), and the module can extend the base class with ClassMethods itself, so one include delivers both instance methods and class methods. It is the standard way around the fact that include alone gives no class methods.

Comparable: one method, six operators

Comparable is one of Ruby's most useful mixins. Define <=> in your class and include Comparable, and you get <, <=, ==, >, >= plus between? and clamp for free. <=> must return -1, 0 or 1, and nil when the other object cannot be compared, such as 5. When you return nil, Comparable raises a clean ArgumentError; if you forget the check, a call such as other.major fails with a NoMethodError instead.

comparable_version.rb
class Version
  include Comparable

  attr_reader :major, :minor

  def initialize(text)
    @major, @minor = text.split(".").map(&:to_i)
  end

  def <=>(other)
    return nil unless other.is_a?(Version)

    [major, minor] <=> [other.major, other.minor]
  end

  def to_s = "#{major}.#{minor}"
end

versions = %w[1.10 1.2 2.0].map { |text| Version.new(text) }
puts versions.sort.join(" ")                       # 1.2 1.10 2.0
puts versions.max                                  # 2.0
puts Version.new("1.2") < Version.new("1.10")      # true
puts Version.new("1.2") == Version.new("1.2")      # true
puts Version.new("1.5").between?(Version.new("1.0"), Version.new("2.0"))   # true
puts Version.new("3.0").clamp(Version.new("1.0"), Version.new("2.0"))      # 2.0
begin
  Version.new("1.0") < 5
rescue ArgumentError => e
  puts e.message                                   # comparison of Version with 5 failed
end
p(Version.new("1.0") == 5)                         # false

In real projects

Where this shows up in real projects

Ruby's standard library is itself built from modules. Array and Hash include Enumerable, which is why map, select and reduce work on both. String and Integer include Comparable, and Kernel supplies puts and require to every object. Utility methods such as Math.sqrt are called directly on a module.

Every gem puts its names inside a namespace so they cannot collide with yours: Net::HTTP, JSON::ParserError and Rails::Application are examples. In Rails, ActiveSupport::Concern makes included modules tidier, and test frameworks use modules such as Minitest::Assertions. When mixins pile up, finding where a method comes from gets hard, so use obj.method(:name).owner and ancestors to find out; when two modules define the same method name, the order in ancestors decides which one wins.

Common mistakes

Common mistakes

1. Expecting include to provide class methods

After include Helpers in class Foo, Foo.new.util works but Foo.util raises NoMethodError, "undefined method 'util' for class Foo". Use extend Helpers for class methods, or the included hook with base.extend(ClassMethods) when you need both.

2. Trying to instantiate or inherit from a module

Swimmer.new raises NoMethodError, and class Foo < Swimmer raises TypeError, "superclass must be an instance of Class (given an instance of Module)". To use a module you must include, extend or prepend it inside a class.

3. A mixin that silently depends on its host

A NeedsName module that calls name on a Bare class lacking name fails only when the method is called, with NameError, "undefined local variable or method 'name' for an instance of Bare"; including it raised nothing. Put a comment at the top of the module, or declare the required method with NotImplementedError.

4. Defining <=> without including Comparable

With <=> but no Comparable, sort still works, but a < b raises NoMethodError, "undefined method '<' for an instance of P", and a == b compares object identity only, so it is false even for equal values. When you write <=>, add include Comparable too.

Best practices

Best practices

  • Put every class you write inside a namespace module, especially anything you will share as a gem or library.
  • Give each mixin one clear job and a name that describes an ability, such as Swimmer or Printable.
  • State what a mixin expects from its host, for example that it needs title and year.
  • When you define <=>, include Comparable and return nil for objects that cannot be compared.

Mini challenge

Mini challenge: a Library namespace

Inside a Library namespace, write a Printable mixin and a Book class that includes Comparable, then add a module method that finds the oldest book.

  • Library::Printable has a print_line method that uses title and year to return text like "Dune (1965)"
  • Library::Book includes Comparable and Printable, with title and year readers and initialize(title, year)
  • <=> compares by year first and then by title
  • Library.oldest(books) returns the oldest book; then print the sorted print_line values and Book.ancestors.first(3)
library.rb
module Library
  # TODO: module Printable with print_line (uses title and year)

  class Book
    # TODO: include Comparable and Printable
    # TODO: readers, initialize(title, year)
    # TODO: <=> by year, then by title
  end

  # TODO: def self.oldest(books)
end

# TODO: build three Library::Book objects with different years
# TODO: print the oldest, the sorted lines and the first 3 ancestors

Expected: Expected output: Emma (1815) Emma (1815) Ulysses (1922) Dune (1965) [Library::Book, Library::Printable, Comparable]

Show hint

Arrays compare element by element, so [year, title] <=> [other.year, other.title] does the job. With Comparable included, books.min gives the oldest. Remember that the module included last appears first in ancestors.

Show solution
library.rb
module Library
  module Printable
    def print_line = "#{title} (#{year})"
  end

  class Book
    include Comparable
    include Printable

    attr_reader :title, :year

    def initialize(title, year)
      @title = title
      @year = year
    end

    def <=>(other)
      [year, title] <=> [other.year, other.title]
    end
  end

  def self.oldest(books) = books.min
end

books = [
  Library::Book.new("Dune", 1965),
  Library::Book.new("Emma", 1815),
  Library::Book.new("Ulysses", 1922)
]

puts Library.oldest(books).print_line
puts books.sort.map(&:print_line)
p Library::Book.ancestors.first(3)

Quick quiz 1 / 3

With module A; end, module B; end and class C; include A; include B; end, what does C.ancestors.first(3) return?

Quick quiz 2 / 3

Given module Shout; def speak = super.upcase; end, class Animal; def speak = "hi"; end and class Dog < Animal; prepend Shout; def speak = "woof"; end, what does Dog.new.speak return?

Quick quiz 3 / 3

class P defines <=> but does not include Comparable. With a = P.new(1) and b = P.new(2), what does a < b do?

What to remember

  • A module is a bundle of methods and constants that cannot be instantiated: as a namespace it prevents name collisions, and as a mixin it shares behaviour across classes.
  • include places a module behind the class, prepend in front of it, and extend gives it to one object or as class methods; Class.ancestors shows the order.
  • module_function makes utility methods callable on the module itself, and gives including classes a private copy.
  • Define <=> and include Comparable to get <, ==, between? and clamp, returning nil when objects cannot be compared.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Modules & Mixins | Thuta Learning