The Forwardable module in Ruby — Part II
In this article we’re going to explore the following topics:
- The
SingleForwardable
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 theForwardable
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.newprinter.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 theSingleForwardable
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
endmodule Facade
extend SingleForwardable
def_delegator :Implementation, :service
endFacade.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 - 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
Thank you for taking the time to read this post :-)
Feel free to 👏 and share this Medium post if it has been useful for you.
Here is a link to my last medium post: The Forwardable module: Part I