Extend Ruby classes with mixins and refinements

8 steps · about 2 h 5 min · Intermediate

  1. See what a module is for (tutorial, Ruby User's Guide, 10 min)

    A short classic introduction to modules as namespaces and mixins.

  2. Define modules, classes and singleton methods (reference, Ruby docs, 20 min)

    The official syntax guide to modules, classes, inheritance and singleton classes.

  3. 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.

  4. 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.

  5. Get comparison methods from one <=> method (reference, Ruby docs, 10 min)

    The model mixin: define <=> and receive <, ==, between? and clamp for free.

  6. Delegate methods instead of inheriting (reference, Ruby docs, 10 min)

    def_delegators keeps composition readable without hand-written wrapper methods.

  7. Patch a core class safely with refinements (reference, Ruby docs, 20 min)

    Refinements scope monkey patches to files that opt in with using.

  8. 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.