Classes
Crystal Modules as Mixins
Modules as Mixins
Crystal modules act as mixins for shared behavior.
Understanding Modules in Crystal
In Crystal, modules are a powerful way to encapsulate shared behavior and functionality that can be reused across multiple classes. Unlike classes, modules cannot be instantiated. Instead, they work as a great mechanism for mixins, allowing you to inject methods and constants into classes.
Defining a Module
Let's start by defining a simple module. This module will contain a method that can be shared across different classes. We'll explore how to use this module as a mixin in a class.
Using Modules as Mixins in Classes
To use a module as a mixin, you include it in a class. This adds the module's methods as instance methods of the class. Here's how you can include the Greetable
module in a class:
Mixins with Multiple Modules
You can include multiple modules in a single class. This is useful for composing complex behaviors by combining simpler modules. For example:
Overriding Module Methods
When you include a module, you can also override its methods in the class if needed. This allows for customization of the behavior defined in the module. Consider the following example:
Conclusion
Modules in Crystal provide a flexible way to share behavior across classes without resorting to inheritance. By using modules as mixins, developers can keep their code DRY (Don't Repeat Yourself) and modular. This is particularly useful when you want to compose classes with shared behavior while maintaining the ability to override and customize functionality.
Classes
- Classes
- Structs
- Inheritance
- Modules as Mixins
- Enums
- Previous
- Inheritance
- Next
- Enums