Module: SingleForwardable

Defined in:
lib/forwardable.rb

Overview

The SingleForwardable module provides delegation of specified methods to a designated object, using the methods #def_delegator and #def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.

Also see the example at forwardable.rb.

Instance Method Summary collapse

Instance Method Details

#def_singleton_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 example at forwardable.rb.



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/forwardable.rb', line 199

def def_singleton_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)

  instance_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_singleton_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:

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

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

See the example at forwardable.rb.



186
187
188
189
190
# File 'lib/forwardable.rb', line 186

def def_singleton_delegators(accessor, *methods)
  for method in methods
    def_singleton_delegator(accessor, method)
  end
end