Skip to content

Instantly share code, notes, and snippets.

@shepmaster
Forked from practicingruby/refactoring patterns
Created October 2, 2010 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shepmaster/607892 to your computer and use it in GitHub Desktop.
Save shepmaster/607892 to your computer and use it in GitHub Desktop.
# Replace Inheritance with Delegation
# http://refactoring.com/catalog/replaceInheritanceWithDelegation.html
# class Roster < Array
# attr_accessor :title
# def to_s
# out = "#{title}\n"
# each do |item|
# out += "#{item}\n"
# end
# return out
# end
# end
# class Roster
# attr_accessor :title
# def initialize
# @people = Array.new
# end
# def <<(person)
# @people << person
# end
# def [](index)
# @people[index]
# end
# def size
# @people.size
# end
# def each
# @people.each {|p| yield(p)}
# end
# def to_s
# out = "#{title}\n"
# each do |item|
# out += "#{item}\n"
# end
# return out
# end
# end
require 'forwardable'
class Roster
extend Forwardable
attr_accessor :title
def initialize
@people = Array.new
end
def_delegators :@people, :<<, :[], :size, :each
def to_s
out = "#{title}\n"
each do |item|
out += "#{item}\n"
end
return out
end
end
require 'test/unit'
class RosterTest < Test::Unit::TestCase
def setup
@roster = Roster.new
@roster.title = "Employees"
@roster << "Joe"
end
def test_size
assert_equal(1, @roster.size)
end
def test_index
assert_equal("Joe", @roster[0])
end
def test_to_s
assert_equal("Employees\nJoe\n", @roster.to_s)
end
end
@shepmaster
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment