Skip to content

Commit

Permalink
Replace Type Code with Module Extension.
Browse files Browse the repository at this point in the history
  • Loading branch information
josemotanet committed Jun 4, 2013
1 parent 3b457c1 commit 49e3e1a
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
37 changes: 37 additions & 0 deletions replace-type-code-with-module-extension/lib/after.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Employee
def initialize(type: :regular)
@type = type
end

def base_salary
500.0
end

def salary
base_salary + bonus
end

def self.build(type: :regular)
instance = new
instance.extend const_get(type.capitalize)
end

end

module Regular
def bonus
0
end
end

module Manager
def bonus
800
end
end

module Boss
def bonus
1500
end
end
28 changes: 28 additions & 0 deletions replace-type-code-with-module-extension/lib/before.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Employee
def initialize(type: :regular)
@type = type
end

def base_salary
500.0
end

def salary
base_salary + bonus
end

private

def self.build(type: :regular)
new type: type
end

def bonus
value = case @type
when :regular then 0
when :boss then 1500.0
when :manager then 800.0
end
end

end
19 changes: 19 additions & 0 deletions replace-type-code-with-module-extension/test/test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,22 @@

require 'before' if ENV["BEFORE"]
require 'after' unless ENV["BEFORE"]

describe Employee do
describe "a regular one" do
it "has a salary" do
Employee.build.salary.must_equal 500.0
end
end

describe "a boss" do
it "has a salary" do
Employee.build(type: :boss).salary.must_equal 2000.0
end
end
describe "a manager" do
it "has a salary" do
Employee.build(type: :manager).salary.must_equal 1300.0
end
end
end

0 comments on commit 49e3e1a

Please sign in to comment.