Skip to content
Modules as Mixins
step 1/6

Reading — step 1 of 6

Learn

~1 min readModules and Classes

A module is a namespace + a bag of methods. You can't instantiate a module — you include it into a class to share its methods.

module Greetable
  def hello
    "Hello, #{name}!"
  end
end

class Person
  include Greetable    # Person now has the hello method
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

Person.new("Ada").hello   # "Hello, Ada!"

include adds the module's methods as instance methods. extend adds them as class methods:

class User
  extend SomeModule      # SomeModule's methods become User.method (class-level)
  include OtherModule    # OtherModule's methods become user.method (instance-level)
end

Modules as namespaces:

module MyApp
  module Utils
    def self.format(s); ...; end
  end
end

MyApp::Utils.format("hi")

The Comparable and Enumerable modules in core Ruby are mixin patterns at their best — implement <=> to get all comparison operators free; implement each to get the entire iteration toolkit.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…