The Forwardable module provides delegation of specified methods to a designated object, using the methods #def_delegator and #def_delegators.
Add this line to your application's Gemfile:
gem'forwardable'And then execute:
$ bundleOr install it yourself as:
$ gem install forwardableFor 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:
require'forwardable'classRecordCollectionattr_accessor:recordsextendForwardabledef_delegator:@records,:[],:record_numberendWe can use the lookup method like so:
r=RecordCollection.newr.records=[4,5,6]r.record_number(0)# => 4Further, if you wish to provide the methods #size, #<<, and #map, all of which delegate to @records, this is how you can do it:
classRecordCollection# re-open RecordCollection classdef_delegators:@records,:size,:<<,:mapendr=RecordCollection.newr.records=[1,2,3]r.record_number(0)# => 1r.size# => 3r << 4# => [1, 2, 3, 4]r.map{ |x| x * 2}# => [2, 4, 6, 8]You can even extend regular objects with Forwardable.
my_hash=Hash.newmy_hash.extendForwardable# prepare object for delegationmy_hash.def_delegator"STDOUT","puts"# add delegation for STDOUT.puts()my_hash.puts"Howdy!"After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/forwardable.
The gem is available as open source under the terms of the 2-Clause BSD License.