Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Classes and Modules

Modules and Mixins

Use Crystal modules as namespaces and as mixins with include and extend, add shared behaviour such as Comparable and Enumerable to your own classes, and organise code across files.

A module is a named bundle of methods and constants. It does two jobs in Crystal. As a namespace it keeps names from colliding (Math::PI, HTTP::Client). As a mixin it lets unrelated classes share behaviour without inheritance. This lesson covers both, plus the standard modules Comparable and Enumerable that turn a few methods into dozens.

Crystal listings are read-only here. Ruby modules work the same way, so the Ruby stand-ins are close matches; differences are noted where they matter.

Modules as namespaces

CRYSTAL
module Geometry
  PI_ISH = 3.14

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

  class Square
    def initialize(@side : Float64)
    end

    def area : Float64
      @side * @side
    end
  end
end

puts Geometry.circle_area(2.0)       # 12.56
puts Geometry::Square.new(3.0).area  # 9.0
puts Geometry::PI_ISH                # 3.14

A def self.name inside a module is a module method, called on the module itself. Geometry::Square is a class that lives inside the namespace and does not clash with another Square elsewhere. Libraries always wrap their code in a module with their name for exactly this reason.

Modules as mixins: include

A module with ordinary instance methods can be mixed into a class with include. The class gains those methods.

CRYSTAL
module Greeter
  def greet : String
    "Hello, I am #{name}"
  end
end

class Person
  include Greeter
  getter name : String

  def initialize(@name)
  end
end

class Robot
  include Greeter

  def name : String
    "R2"
  end
end

puts Person.new("Ada").greet   # Hello, I am Ada
puts Robot.new.greet           # Hello, I am R2

Person and Robot share no parent class, yet both get greet. The module expects the including class to provide name, and the compiler checks that for every class that includes it.

You can declare that expectation with an abstract method inside the module, so the error appears in the right place:

CRYSTAL
module Greeter
  abstract def name : String

  def greet : String
    "Hello, I am #{name}"
  end
end

A class may include many modules, and modules can include other modules.

Ruby Stand-in: a mixin shared by unrelated classes in Ruby

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.

extend: class-level mixins

extend adds the module's methods to the class itself, as class methods:

CRYSTAL
module Finders
  def find_by_name(items : Array, name : String)
    items.find { |item| item.name == name }
  end
end

class Product
  extend Finders
  getter name : String

  def initialize(@name)
  end
end

products = [Product.new("pen"), Product.new("ink")]
puts Product.find_by_name(products, "ink").try(&.name)   # ink

Remember it this way: include gives instances new methods, extend gives the class new methods.

Comparable: one method, six operators

The standard Comparable module needs only <=>. It then gives you <, <=, >, >=, ==, between? and clamp.

CRYSTAL
class Version
  include Comparable(Version)
  getter major : Int32
  getter minor : Int32

  def initialize(@major, @minor)
  end

  def <=>(other : Version) : Int32
    {major, minor} <=> {other.major, other.minor}
  end
end

a = Version.new(1, 4)
b = Version.new(2, 0)
puts a < b                 # true
puts a == Version.new(1, 4) # true
puts [b, a].min.minor      # 4

Comparable(T) is a generic module: you tell it which type you compare against.

Enumerable: collection methods for free

Enumerable needs one method, each, and in return you get map, select, reduce, sort_by, min, max, first, includes?, to_a and many more.

CRYSTAL
class Playlist
  include Enumerable(String)

  def initialize(@songs : Array(String))
  end

  def each(& : String ->)
    @songs.each { |song| yield song }
  end
end

list = Playlist.new(["Intro", "Verse", "Outro"])
puts list.map(&.upcase)               # ["INTRO", "VERSE", "OUTRO"]
puts list.select { |s| s.size > 4 }   # ["Intro", "Verse", "Outro"]
puts list.includes?("Verse")          # true
puts list.first                       # Intro
puts list.size                        # 3

Defining each with yield is all it takes. This pattern, a small contract giving a big feature set, is how much of the Crystal standard library works.

Ruby Stand-in: Comparable and Enumerable in Ruby

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.

Hooks and modules with data

A module can hold constants and can define macros (see the macros chapter) that run when it is included, using the included hook:

CRYSTAL
module Trackable
  macro included
    @@instances = 0

    def self.instances
      @@instances
    end
  end
end

class Widget
  include Trackable
end

Hooks like included, extended and inherited are Crystal's compile-time equivalents of Ruby's self.included(base), and they power much of the metaprogramming in frameworks.

Organising code across files

A project usually keeps one top-level module per library and one file per class, then pulls files together with require:

CRYSTAL
# src/geometry.cr
require "./geometry/square"
require "./geometry/circle"

module Geometry
  VERSION = "0.1.0"
end

require "./x" is relative to the current file; require "json" looks in the standard library and the lib folder where shards are installed. Each file is loaded once, no matter how many times it is required.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does include SomeModule inside a class do?

    include mixes the methods into instances; extend adds them to the class itself.
  2. 2. Which single method must a class define to use Comparable(T)?

    Comparable derives <, <=, >, >=, == and more from <=>.
  3. 3. Which method must a class define to use Enumerable?

    With each (which yields every element), Enumerable provides map, select, reduce and many others.
  4. 4. Why do libraries wrap their code in a module?

    A module namespace keeps names such as Client or Parser from clashing between libraries.

Summary

  • A module is a namespace (Module::Name) and a bundle of reusable methods.
  • include mixes instance methods into a class; extend adds class-level methods.
  • Comparable (needs <=>) and Enumerable (needs each) add many methods to your own types.
  • Modules can declare abstract def to state what an including class must provide.
  • require loads files once; wrap your library in a module named after it.

Next: Generics and Enums