-
Notifications
You must be signed in to change notification settings - Fork 11
/
nanomart.rb
executable file
·155 lines (129 loc) · 2.81 KB
/
nanomart.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# you can buy just a few things at this nanomart
require 'highline'
class Nanomart
class NoSale < StandardError; end
def initialize(logfile, prompter)
@logfile, @prompter = logfile, prompter
end
def sell_me(itm_type)
itm = case itm_type
when :beer
Item::Beer.new(@logfile, @prompter)
when :whiskey
Item::Whiskey.new(@logfile, @prompter)
when :cigarettes
Item::Cigarettes.new(@logfile, @prompter)
when :cola
Item::Cola.new(@logfile, @prompter)
when :canned_haggis
Item::CannedHaggis.new(@logfile, @prompter)
else
raise ArgumentError, "Don't know how to sell #{itm_type}"
end
itm.rstrctns.each do |r|
itm.try_purchase(r.ck)
end
itm.log_sale
end
end
class HighlinePrompter
def get_age
HighLine.new.ask('Age? ', Integer) # prompts for user's age, reads it in
end
end
module Restriction
DRINKING_AGE = 21
SMOKING_AGE = 18
class DrinkingAge
def initialize(p)
@prompter = p
end
def ck
age = @prompter.get_age
if age >= DRINKING_AGE
true
else
false
end
end
end
class SmokingAge
def initialize(p)
@prompter = p
end
def ck
age = @prompter.get_age
if age >= SMOKING_AGE
true
else
false
end
end
end
class SundayBlueLaw
def initialize(p)
@prompter = p
end
def ck
# pp Time.now.wday
# debugger
Time.now.wday != 0 # 0 is Sunday
end
end
end
class Item
INVENTORY_LOG = 'inventory.log'
def initialize(logfile, prompter)
@logfile, @prompter = logfile, prompter
end
def log_sale
File.open(@logfile, 'a') do |f|
f.write(nam.to_s + "\n")
end
end
def nam
class_string = self.class.to_s
short_class_string = class_string.sub(/^Item::/, '')
lower_class_string = short_class_string.downcase
class_sym = lower_class_string.to_sym
class_sym
end
def try_purchase(success)
if success
return true
else
raise Nanomart::NoSale
end
end
class Beer < Item
def rstrctns
[Restriction::DrinkingAge.new(@prompter)]
end
end
class Whiskey < Item
# you can't sell hard liquor on Sundays for some reason
def rstrctns
[Restriction::DrinkingAge.new(@prompter), Restriction::SundayBlueLaw.new(@prompter)]
end
end
class Cigarettes < Item
# you have to be of a certain age to buy tobacco
def rstrctns
[Restriction::SmokingAge.new(@prompter)]
end
end
class Cola < Item
def rstrctns
[]
end
end
class CannedHaggis < Item
# the common-case implementation of Item.nam doesn't work here
def nam
:canned_haggis
end
def rstrctns
[]
end
end
end