Name

Forwardable — Module to add selected method delegations to a class

Synopsis

The Forwardable module provides more explicit method delegation. You can specify method name and destination object explicitly.

Required Library

require “forwardable”

Example

class Foo
  extend Forwardable
  # ...
  def_delegators("@out", "printf", "print")
  def_delegators(:@in, :gets)
  def_delegator(:@contents, :[], "content_at")
end
f = Foo.new
f.printf("hello world\n")   # forward to @out.printf
f.gets                      # forward to @in.gets
f.content_at(1)             # forward to @contents.[]

Instance Methods

f.def_delegator(accessor, method[, alt=method])
f.def_instance_delegator(accessor, method[, alt=method])

Defines delegation from method to accessor. If alt is specified, alt method is called instead of method.

f.def_delegators(accessor, method...)
f.def_instance_delegators(accessor, method...)

Defines delegation to accessor for each method.

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.