RubyCademy
Published in

RubyCademy

Photo by Jaime Dantas on Unsplash

The SingleForwardable module

  • The SingleForwardable module
  • Add behavior to an object
  • Add behavior to a class or a module

The SingleForwardable module

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

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!"
?> ruby single_forwardable.rb
Howdy!

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
$> ruby single_forwardable.rb
serviced!
  • as first argument the :Implementation class as receiver
  • as second argument the :service message

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 😅).

--

--

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