TExcelTAD
Home › Ruby › Ruby Modules & Mixins

Ruby Modules & Mixins

A module is a container for methods and constants. Unlike a class, a module cannot create objects. Modules have two big jobs in Ruby:

  1. Namespaces — grouping related classes, methods and constants under one name.
  2. Mixins — sharing behaviour between classes that are not related by inheritance.

Modules as namespaces

ruby · try it yourself
module Geometry
  PI_ISH = 3.14

  def self.circle_area(r)
    PI_ISH * r * r
  end

  class Point
    attr_reader :x, :y

    def initialize(x, y)
      @x, @y = x, y
    end

    def to_s = "(#{x}, #{y})"
  end
end

p Geometry.circle_area(2)
p Geometry::PI_ISH
puts Geometry::Point.new(3, 4)
12.56
3.14
(3, 4)

The :: operator reaches into a module. Namespaces prevent name clashes: your Geometry::Point and a library's Graphics::Point can live side by side.

Math is a built-in module used the same way: Math.sqrt(16), Math::PI.

Mixins with include

A class can include any number of modules. The module's methods become instance methods of the class:

ruby · try it yourself
module Greetable
  def greet
    "Hello, I'm #{name}"
  end
end

module Trackable
  def track(event)
    @events ||= []
    @events << event
    "#{name} logged #{event} (#{@events.size} total)"
  end
end

class Customer
  include Greetable
  include Trackable
  attr_reader :name

  def initialize(name) = @name = name
end

class Robot
  include Greetable
  def name = "RX-78"
end

c = Customer.new("Ines")
puts c.greet
puts c.track("login")
puts c.track("purchase")
puts Robot.new.greet
p Customer.include?(Trackable)
Hello, I'm Ines
Ines logged login (1 total)
Ines logged purchase (2 total)
Hello, I'm RX-78
true

Greetable only relies on the class having a name method. Customer and Robot share the behaviour without sharing a parent class — that's the power of mixins.

Where included modules go

An included module is inserted into the ancestor chain right above the class. Method lookup goes: the class → its modules (last included first) → the superclass → …

ruby · try it yourself
module Loud
  def speak = super.upcase + "!!"
end

class Animal
  def speak = "hello"
end

class Parrot < Animal
  include Loud
end

p Parrot.ancestors.take(4)
p Parrot.new.speak
[Parrot, Loud, Animal, Object]
"HELLO!!"

Because Loud sits between Parrot and Animal, its super calls Animal#speak.

prepend

prepend puts the module before the class in the chain, so the module's method runs first and can wrap the class's own method:

ruby · try it yourself
module Logging
  def checkout(total)
    puts "-> checkout(#{total})"
    result = super
    puts "<- #{result}"
    result
  end
end

class Shop
  prepend Logging

  def checkout(total)
    "charged #{total}"
  end
end

Shop.new.checkout(30)
p Shop.ancestors.take(3)
-> checkout(30)
<- charged 30
[Logging, Shop, Object]

extend: module methods on one object or class

extend adds the module's methods to a single object — or, when used inside a class, as class methods:

ruby · try it yourself
module Describable
  def describe = "I am #{self}"
end

obj = "plain string"
obj.extend(Describable)
puts obj.describe

class Config
  extend Describable
end
puts Config.describe
I am plain string
I am Config
Keyword Module methods become…
include M instance methods (after the class in lookup)
prepend M instance methods (before the class in lookup)
extend M methods of that one object / class methods

Module functions

Utility modules often define methods with self. (or module_function) so they can be called directly on the module:

ruby · try it yourself
module TextTools
  module_function

  def slugify(text)
    text.downcase.strip.gsub(/[^a-z0-9]+/, "-").gsub(/^-|-$/, "")
  end

  def initials(name)
    name.split.map { |w| w[0].upcase }.join
  end
end

p TextTools.slugify("  Hello, Ruby World! ")
p TextTools.initials("grace brewster hopper")
"hello-ruby-world"
"GBH"

Hook: included

A module can react when it is included. Libraries use this to add class methods at the same time:

ruby · try it yourself
module Countable
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def instances = @instances ||= 0
    def count_new! = @instances = instances + 1
  end

  def initialize(*)
    self.class.count_new!
    super
  end
end

class Ticket
  include Countable
end

3.times { Ticket.new }
p Ticket.instances
3

Tip: Name mixin modules after an ability, often ending in -able: Comparable, Enumerable, Printable, Serializable. The next lesson shows Ruby's two most famous built-in mixins.

Test yourself

Can you create an object with MyModule.new?

  1. Yes, like a class
  2. No, modules cannot be instantiated
  3. Only if it includes initialize
  4. Only with extend

What does include Greetable inside a class do?

  1. Copies the file
  2. Makes the module's methods available as instance methods
  3. Makes them class methods
  4. Inherits from the module

Which keyword places a module before the class in the method lookup chain?

  1. include
  2. extend
  3. prepend
  4. require