Crystal Notes: Modules
Updated: 17th of August 2021
Published: 30th of July 2021
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.
# 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.
# 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.
# 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
Modules can be used to "mixin" behavour.
# 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
- Library authors should use modules to help avoid namespace collisions.