Crystal Notes: Modules
Updated: 2021-08-17
Published: 2021-07-30
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::ThingsTop 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 # => thingsTop 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 # => stuffMixin
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.stuffConsiderations
- Library authors should use modules to help avoid namespace collisions.
Links
https://pragprog.com/titles/crystal/programming-crystal/
https://crystal-lang.org/reference/syntax_and_semantics/modules.html