Extend Ruby classes with mixins and refinements
8 steps · about 2 h 5 min · Intermediate
- See what a module is for (tutorial, Ruby User's Guide, 10 min)
A short classic introduction to modules as namespaces and mixins.
- Define modules, classes and singleton methods (reference, Ruby docs, 20 min)
The official syntax guide to modules, classes, inheritance and singleton classes.
- Use include, prepend and the method lookup chain (reference, Ruby docs, 25 min)
Module documents include, prepend, ancestors and module_function, the core mixin tools.
- Add methods to one object with extend (reference, Ruby docs, 10 min)
Object#extend and singleton methods show how a module can decorate a single instance.
- Get comparison methods from one <=> method (reference, Ruby docs, 10 min)
The model mixin: define <=> and receive <, ==, between? and clamp for free.
- Delegate methods instead of inheriting (reference, Ruby docs, 10 min)
def_delegators keeps composition readable without hand-written wrapper methods.
- Patch a core class safely with refinements (reference, Ruby docs, 20 min)
Refinements scope monkey patches to files that opt in with using.
- Follow community style for modules and mixins (article, Ruby Style Guide, 20 min)
The community style guide's class and module rules keep mixins predictable.