Skip to content

Repository files navigation

Forwardable

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

Installation

Add this line to your application's Gemfile:

gem'forwardable'

And then execute:

$ bundle

Or install it yourself as:

$ gem install forwardable

Usage

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:

require'forwardable'classRecordCollectionattr_accessor:recordsextendForwardabledef_delegator:@records,:[],:record_numberend

We can use the lookup method like so:

r=RecordCollection.newr.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:

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!"

Development

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.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ruby/forwardable.

License

The gem is available as open source under the terms of the 2-Clause BSD License.

About

Provides delegation of specified methods to a designated object

Topics

Resources

Security policy

Stars

45 stars

Watchers

30 watching

Forks

Releases

Packages

Used by

Contributors

Languages