Skip to content

Instantly share code, notes, and snippets.

@carols10cents
Forked from practicingruby/refactoring patterns
Created October 2, 2010 19:35
Show Gist options
  • Save carols10cents/607917 to your computer and use it in GitHub Desktop.
Save carols10cents/607917 to your computer and use it in GitHub Desktop.
# Pattern: Replace exception with test
class PreRefactoringRoster
def initialize
@members = []
end
attr_reader :members
def add_user(name)
begin
add_user_to_game(name)
rescue Exception => e
add_user_to_game(name + rand(10000).to_s)
end
@members.last
end
private
def add_user_to_game(this_name)
# totally contrived
if @members.find{|n| n.name.eql?(this_name)}
raise "A player already has this username"
else
@members << Person.new(this_name)
end
end
end
class PostRefactoringRoster
def initialize
@members = []
end
attr_reader :members
def add_user(name)
if @members.find{|n| n.name.eql?(name)}
add_user_to_game(name + rand(10000).to_s)
else
add_user_to_game(name)
end
@members.last
end
private
def add_user_to_game(this_name)
# totally contrived
if @members.find{|n| n.name.eql?(this_name)}
raise "A player already has this username"
else
@members << Person.new(this_name)
end
end
end
class Person
def initialize(name)
@name = name
end
attr_reader :name
end
require "spud"
describe "pre refactoring" do
before(:each) do
@roster = PreRefactoringRoster.new
end
it "should add a random number to the username if you try to add it 2x" do
@roster.add_user("Carol")
@roster.add_user("Carol").name.should match(/Carol\d+/)
end
end
describe "post refactoring" do
before(:each) do
@roster = PostRefactoringRoster.new
end
it "should add a random number to the username if you try to add it 2x" do
@roster.add_user("Carol")
@roster.add_user("Carol").name.should match(/Carol\d+/)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment