Module: Forwardable

Defined in:
lib/forwardable.rb

Overview

The Forwardable module provides delegation of specified methods to a designated object, using the methods #def_delegator and #def_delegators.

For example, say you have a class RecordCollection which contains an array @records. You could provide the lookup method #record_number(), which simply calls #[] on the @records array, like this:

class RecordCollection
  extend Forwardable
  def_delegator :@records, :[], :record_number
end

Further, if you wish to provide the methods #size, #<<, and #map, all of which delegate to @records, this is how you can do it:

class RecordCollection
  # extend Forwardable, but we did that above
  def_delegators :@records, :size, :<<, :map
end

Also see the example at forwardable.rb.

Class Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.debugObject

force Forwardable to show up in stack backtraces of delegated methods



114
115
116
# File 'lib/forwardable.rb', line 114

def debug
  @debug
end

Instance Method Details

#def_instance_delegator(accessor, method, ali = method) ⇒ Object Also known as: def_delegator

Defines a method method which delegates to obj (i.e. it calls the method of the same name in obj). If new_name is provided, it is used as the name for the delegate method.

See the examples at Forwardable and forwardable.rb.



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/forwardable.rb', line 143

def def_instance_delegator(accessor, method, ali = method)
  accessor = accessor.id2name if accessor.kind_of?(Integer)
  method = method.id2name if method.kind_of?(Integer)
  ali = ali.id2name if ali.kind_of?(Integer)

  module_eval(<<-EOS, "(__FORWARDABLE__)", 1)
    def #{ali}(*args, &block)
	begin
 #{accessor}.__send__(:#{method}, *args, &block)
	rescue Exception
 [email protected]_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug
 Kernel::raise
	end
    end
  EOS
end

#def_instance_delegators(accessor, *methods) ⇒ Object Also known as: def_delegators

Shortcut for defining multiple delegator methods, but with no provision for using a different name. The following two code samples have the same effect:

def_delegators :@records, :size, :<<, :map

def_delegator :@records, :size
def_delegator :@records, :<<
def_delegator :@records, :map

See the examples at Forwardable and forwardable.rb.



130
131
132
133
134
# File 'lib/forwardable.rb', line 130

def def_instance_delegators(accessor, *methods)
  for method in methods
    def_instance_delegator(accessor, method)
  end
end