Modules and mixins

Define a module

The keyword module groups methods and constants under one name. Unlike a class, a module cannot be instantiated on its own. Classes later borrow the grouped behavior through include or extend.

module Loud def shout(text) puts text.upcase end end puts Loud.class

Module

Include a mixin

Writing include inside a class mixes the module methods in as instance methods. Every instance then answers to the shared behavior. The class body stays short while the module carries the reusable part.

module Loud def shout(text) puts text.upcase end end class User include Loud end User.new.shout("hello")

HELLO

Extend with class methods

Writing extend inside a class mixes the module methods in as class methods instead. This placement suits finders, builders, and other helpers that belong to the class itself. Instances remain untouched by the mixed behavior.

module Finder def find(id) puts "found #{id}" end end class User extend Finder end User.find(7)

found 7

Modules as namespaces

Modules also fence off names: nesting classes and constants inside keeps each name scoped. A Cart defined inside Shop is addressed as Shop::Cart and never clashes with a Cart from another library.

module Shop class Cart def size 0 end end end puts Shop::Cart.new.size

0

Next: Classes and objects

Article author: Arthur Isaev

Banner image