| Module | Forwardable |
| In: |
lib/forwardable.rb
|
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
f = Foo.new
f.printf ...
f.gets
f.content_at(1)
Also see the example at forwardable.rb.
| FORWARDABLE_VERSION | = | "1.0.0" |
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.
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
ruby-doc.org is hosted and run by James Britt and Happy Camper Studios, a Ruby application development company in Phoenix, Arizona. Ruby-doc.org was created in 2002 to promote the Ruby language and to help other Ruby hackers.
Documentation content on ruby-doc.org is provided by remarkable members of the Ruby community.
For more information on the Ruby programming language, visit ruby-lang.org.
Want to help improve Ruby's API docs? See Ruby Documentation Guidelines.