Ruby Mixins – Prepend

12 marca 2025
ruby

Ruby Inheritance and Mixins

Ruby, like any object-oriented language, relies on inheritance. Due to the limitation of inheriting from only one class at a time, the language creators proposed a mechanism of mixins - adding modules to classes. This allows programmers to follow good practices of using composition instead of inheritance.

Using the PREPEND Directive

One way to mix a module into a class is the PREPEND directive.

This directive causes the module to be included in the inheritance chain of objects at its very end, even before the class where we add the mixin. This provides a way to implement a decorator pattern for the class.

If methods with the same name exist in both the module and the class, the method from the module will be called first. If this method contains the super keyword, the next method with the same name in the extended class will be called.

Practical Example

A class prepended with the Logger module allows for implementation of a log method that returns a string. Calling this method executes via super in the module's method, adding a timestamp to the returned string.