-
Notifications
You must be signed in to change notification settings - Fork 36
/
chapter_7.rb
126 lines (99 loc) · 2.29 KB
/
chapter_7.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
############## Page 148 ##############
class Schedule
def scheduled?(schedulable, start_date, end_date)
puts "This #{schedulable.class} " +
"is not scheduled\n" +
" between #{start_date} and #{end_date}"
false
end
end
############## Page 149 ##############
class Bicycle
attr_reader :schedule, :size, :chain, :tire_size
# Inject the Schedule and provide a default
def initialize(args={})
@schedule = args[:schedule] || Schedule.new
# ...
end
# Return true if this bicycle is available
# during this (now Bicycle specific) interval.
def schedulable?(start_date, end_date)
!scheduled?(start_date - lead_days, end_date)
end
# Return the schedule's answer
def scheduled?(start_date, end_date)
schedule.scheduled?(self, start_date, end_date)
end
# Return the number of lead_days before a bicycle
# can be scheduled.
def lead_days
1
end
# ...
end
require 'date'
starting = Date.parse("2015/09/04")
ending = Date.parse("2015/09/10")
b = Bicycle.new
b.schedulable?(starting, ending)
# This Bicycle is not scheduled
# between 2015-09-03 and 2015-09-10
# => true
############## Page 150 ##############
module Schedulable
attr_writer :schedule
def schedule
@schedule ||= ::Schedule.new
end
def schedulable?(start_date, end_date)
!scheduled?(start_date - lead_days, end_date)
end
def scheduled?(start_date, end_date)
schedule.scheduled?(self, start_date, end_date)
end
# includers may override
def lead_days
0
end
end
############## Page 151 ##############
class Bicycle
include Schedulable
def lead_days
1
end
# ...
end
require 'date'
starting = Date.parse("2015/09/04")
ending = Date.parse("2015/09/10")
b = Bicycle.new
b.schedulable?(starting, ending)
# This Bicycle is not scheduled
# between 2015-09-03 and 2015-09-10
# => true
############## Page 152 ##############
class Vehicle
include Schedulable
def lead_days
3
end
# ...
end
class Mechanic
include Schedulable
def lead_days
4
end
# ...
end
v = Vehicle.new
v.schedulable?(starting, ending)
# This Vehicle is not scheduled
# between 2015-09-01 and 2015-09-10
# => true
m = Mechanic.new
m.schedulable?(starting, ending)
# This Mechanic is not scheduled
# between 2015-08-31 and 2015-09-10
# => true