RubyCademy
Published in

RubyCademy

The Forwardable module in Ruby — Part I

In this article we’re going to explore the following topics:

  • the module
  • the method
  • the method
  • the method

The Forwardable module

is a module that can be used to add behavior to all the instances of a given class.

This module is included to the singleton class using the keyword in order to add methods at class-level (to keep it simple).

So let’s break down the API.

The def_delegator method

The method allows an object to forward a message to a defined receiver.

NB: feel free to have a look to my article if you’re unfamiliar with the notion of in Ruby.

Nothing better than example to demystify the previous assertion

produces

This works.. But calling outside of the class definition is a bit.. weirdo !

So let’s encapsulate this code into the class definition

produces

Better ! here the method contains the logic to access to the hero main skill.

This solution is acceptable. But Ruby provides a mechanism to forward a message () from an instance () to an explicit receiver () using the method.

So let’s modify our gist using this method

produces

Cool ! Here we avoid to create a getter method to access by using the message forwarding system provided by Ruby.

First, we require the library.

Then, we in order to add the module methods at class-level.

Then we use the freshly added class-level method :

  • The first argument correspond to the receiver of the message forwarding.
  • The second argument is the message to forward.
  • And finally the third argument is an alias of the message. So, when we call — which is more readable than — then internally the will be automatically called.

The method

The 2 main differences with the method is that it takes a set of methods to forward and the methods cannot be aliased

produces

Here, the and method of the array are available for any instance of .

when one of these 2 methods are called then the message is forwarded to the array.

The method

The method accepts a hash as argument where:

  • the key is one or more messages
  • the value is the receiver of the messages defined as key

produces

Here, the message corresponds to the .

And, the message corresponds to the .

Feel free to have a look to the about the module.

Voilà !

RubyCademy is now available on Youtube! ▶️ 🚀 🤩 💎

We publish short videos (maximum 5 minutes) that talk about technical notions, quick wins and tools (..and a couple of geek stuffs 😅).

Feel free to click on the image below to access our Youtube channel

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store