The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.
forwardable.rb provides single-method delegation via the #def_delegator and #def_delegators methods. For full-class delegation via DelegateClass, see delegate.rb.
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:
1 2 3 4 5 6 7
require'forwardable'
classRecordCollection attr_accessor:records extendForwardable def_delegator :@records, :[], :record_number end
We can use the lookup method like so:
1 2 3
r = RecordCollection.new r.records = [4,5,6] r.record_number(0) # => 4
Further, if you wish to provide the methods size, <<, and map, all of which delegate to @records, this is how you can do it:
1 2 3 4 5 6 7 8 9 10
classRecordCollection# re-open RecordCollection class def_delegators :@records, :size, :<<, :map end
You can even extend regular objects with Forwardable.
1 2 3 4
my_hash = Hash.new my_hash.extendForwardable# prepare object for delegation my_hash.def_delegator "STDOUT", "puts"# add delegation for STDOUT.puts() my_hash.puts "Howdy!"
Another example
You could use Forwardable as an alternative to inheritance, when you don’t want to inherit all methods from the superclass. For instance, here is how you might add a range of Array instance methods to a new class Queue: