Skip to content

Instantly share code, notes, and snippets.

@joebew42
Forked from xpepper/refactoring_example.rb
Created April 5, 2013 14:35
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 joebew42/5319745 to your computer and use it in GitHub Desktop.
Save joebew42/5319745 to your computer and use it in GitHub Desktop.
class Price
attr_reader :price_code
def get_price_code
@price_code
end
def get_charge(days_rented)
# To implement in the subclass
raise NotImplemeted
end
def get_frequent_renter_points(days_rented)
1
end
end
class RegularPrice < Price
def initialize
@price_code = 0
end
def get_charge(days_rented)
result = 2
result += (days_rented - 2) * 1.5 if days_rented > 2
result
end
end
class NewReleasePrice < Price
def initialize
@price_code = 1
end
def get_charge(days_rented)
days_rented * 3
end
def get_frequent_renter_points(days_rented)
# add bonus for a two day new release rental
days_rented > 1 ? 2 : 1
end
end
class ChildrenPrice < Price
def initialize
@price_code = 2
end
def get_charge(days_rented)
result = 1.5
result += (days_rented - 3) * 1.5 if days_rented > 3
result
end
end
class Movie
REGULAR = 0
NEW_RELEASE = 1
CHILDREN = 2
attr_reader :title
attr_reader :price_code
def initialize(title, price_code)
@title = title
@price_code = case price_code
when NEW_RELEASE
NewReleasePrice.new
when CHILDREN
ChildrenPrice.new
else
RegularPrice.new
end
end
def get_charge(days_rented)
@price_code.get_charge days_rented
end
def get_price_code
@price_code.get_price_code
end
def get_frequent_renter_points(days_rented)
@price_code.get_frequent_renter_points days_rented
end
end
class Rental
attr_reader :movie, :days_rented
def initialize(movie, days_rented)
@movie, @days_rented = movie, days_rented
end
def get_charge
@movie.get_charge @days_rented
end
def get_frequent_renter_points
@movie.get_frequent_renter_points @days_rented
end
end
class Customer
attr_reader :name
def initialize(name)
@name = name
@rentals = []
end
def add_rental(arg)
@rentals << arg
end
def get_total_charge
total = 0
@rentals.each { |rental| total += rental.get_charge }
total
end
def get_total_frequent_renter_points
total = 0
@rentals.each { |rental| total += rental.get_frequent_renter_points }
total
end
def statement
result = "Rental Record for #{@name}\n"
@rentals.each do |rental|
# show figures for this rental
result += "\t" + rental.movie.title + "\t" + rental.get_charge.to_s + "\n"
end
#add footer lines
result += "Amount owed is #{get_total_charge}\n"
result += "You earned #{get_total_frequent_renter_points} frequent renter points"
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment