The SingleForwardable module
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.
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à !
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