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

The SingleForwardable module

module Add behavior to an object

Add behavior to a class or a module

NB: feel free to have a look to the Part I if you’re unfamiliar with the Forwardable module in Ruby.

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this link! 🙏

Thank you for your time!

The SingleForwardable module

SingleForwardable is a module, which can be used to add behavior to an object, a class or a module.

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

Add Behavior to an Object

Let’s breakdown the example provided by the official documentation

# in single_forwardable.rb

require 'forwardable' printer = String.new printer.extend SingleForwardable

printer.def_delegator "STDOUT", "puts" printer.puts "Howdy!"

produces

?> ruby single_forwardable.rb

Howdy!

printer is an instance of String .

This object extends the SingleForwardable module. This means that the methods inside the module will be added to the singleton class of the printer object. So, only this specific instance of String will enjoy the properties of the SingleForwardable module.

Then we use the printer.def_delegator method to forward any call to printer.puts to STDOUT (standard output).

That’s why Howdy! is printed out on the terminal.

The Forwardable module can also do so. But for clarity always prefer to use the SingleForwardable module.

Add Behavior to a Class or a Module

Let’s breakdown the example provided by the official documentation

# in single_forwardable.rb

require 'forwardable' class Implementation

def self.service

puts "serviced!"

end

end module Facade

extend SingleForwardable



def_delegator :Implementation, :service

end Facade.service

produces

$> ruby single_forwardable.rb

serviced!

Here the Implementation class defines a class-level method named service .

Then the Facade module extends SingleForwardable .

After, the def_delegator method is called with:

as first argument the :Implementation class as receiver

class as receiver as second argument the :service message

This means that any call to Facade.service will automatically forward the service message to the Implementation receiver

The Forwardable module cannot set a Class/Module as receiver of a forwarded message.

Voilà !

May I have your attention please 🎤🎤

Feel free to subscribe here: www.rubycademy.com