This repository has been archived by the owner on Apr 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_example.rb
104 lines (86 loc) · 1.84 KB
/
first_example.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Ruby Refactoring A first example
class Movie
CHILDRENS = 2
REGULAR = 0
NEW_RELEASE = 1
attr_reader :title
attr_accessor :price_code
def initialize(title, price_code)
@title, @price_code = title, price_code
end
end
class Rental
attr_reader :movie, :days_rented
def initialize(movie, days_rented)
@movie, @days_rented = movie, days_rented
end
def charge
base_charge + extra_charge
end
private
def base_charge
case movie.price_code
when Movie::REGULAR
2
when Movie::CHILDRENS
1.5
when Movie::NEW_RELEASE
days_rented * 3
end
end
def extra_charge
if days_rented > base_period
(days_rented - base_period) * 1.5
else
0
end
end
def base_period
case movie.price_code
when Movie::REGULAR
2
when Movie::CHILDRENS
3
when Movie::NEW_RELEASE
Float::INFINITY
end
end
end
class Customer
attr_reader :name
def initialize(name)
@name = name
@rentals = []
end
def add_rental(arg)
@rentals << arg
end
def statement
total_amount, frequent_renter_points = 0, 0
result = "Rental Record for #{@name}\n"
@rentals.each do |rental|
this_amount = 0
this_amount += rental.charge
frequent_renter_points += points_for_rental(rental)
# show figures for this rental
result += "\t" + rental.movie.title + "\t" + this_amount.to_s + "\n"
total_amount += this_amount
end
# add footer lines
result += "Amount owed is #{total_amount.to_s}\n"
result += "You earned #{frequent_renter_points.to_s} frequent renter points"
result
end
def points_for_rental(rental)
case rental.movie.price_code
when Movie::CHILDRENS, Movie::REGULAR
1
when Movie::NEW_RELEASE
if rental.days_rented > 1
2
else
1
end
end
end
end