Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created January 24, 2010 04:32
Show Gist options
  • Save beccasaurus/285003 to your computer and use it in GitHub Desktop.
Save beccasaurus/285003 to your computer and use it in GitHub Desktop.
Example of using Forwardable with def_delegators

An example of using forwardable for anyone who hasn't used it before.

This is built into Rails via the delegate method (which has some extra features, like creating methods with prefixes and whatnot)

$ ./UsingForwardable.rb
0
2
Thing
Another Thing
require 'forwardable'
class BagOfStuff
extend Forwardable
def_delegators :@stuff, :<<, :length, :each
def initialize
@stuff = []
end
def some; end
def methods; end
def specific; end
def to; end
def a; end
def bag; end
def of; end
def stuff; end
end
stuff = BagOfStuff.new
puts stuff.length
stuff << "Thing"
stuff << "Another Thing"
puts stuff.length
stuff.each do |thing|
puts thing
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment