Intro

Modules in Crystal allow you to group methods and classes together based on related functionality. They provide a namespace to help avoid naming collisions and can also be used to mixin functionality.

Module Definition

crystal
# Define a module that wraps a class.
module Stuff
  class Things
  end
end

# Access a class from within a module.
s = Stuff::Things.new
puts typeof(s) # => Stuff::Things

Top Level Variables

Modules can have top level variables.

crystal
# Define a module with a top level variable.
module Things
  THINGS = "things"
end

# Access the top level variable.
puts Things::THINGS # => things

Top Level Methods

Modules can have top level methods.

crystal
# Define a module with a top level method.
module Things
  # Avoid having to define self.method_name
  # by extending self.
  extend self

  def stuff # self.stuff not required.
    puts("stuff")
  end

end

# Access the top level method.
Things.stuff # => stuff

Mixin

Modules can be used to "mixin" behavour.

crystal
# Define a module
module Stuff
  extend self
  def stuff
    puts "stuff"
  end
end

# Mixin the Stuff module to the Things class.
class Things
  include Stuff
end

# Access the behaviour from the Stuff module in Things.
Things.new.stuff

Considerations

  • Library authors should use modules to help avoid namespace collisions.