-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlamp.rb
86 lines (73 loc) · 1.4 KB
/
lamp.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
require 'yaml/store'
class Lamp
def self.create_database
db = YAML::Store.new('lamps_db.yaml')
db.transaction do
if db['count'].nil? || db['count'].zero?
db['count'] = 0
db['next_id'] = 0
db['all_ids'] = []
end
end
db
end
@@db ||= Lamp.create_database
attr_reader :id
attr_accessor :quantity, :price
def initialize(name, price, quantity)
@name = name
@price = price
@quantity = quantity
end
def self.create(*args)
Lamp.new(*args).save
end
def destroy
@@db.transaction do
if @id.nil?
raise "Cannot delete Lamp that is not persisted!"
end
@@db.delete(@id)
ids = @@db['all_ids']
ids.delete(@id)
@@db['all_ids'] = ids
@@db['count'] -= 1
end
@id = nil
self
end
def save
@@db.transaction do
if @id.nil?
@id = @@db['next_id']
@@db['all_ids'] << @id
@@db['next_id'] += 1
@@db['count'] += 1
end
@@db[@id] = self
end
self
end
def self.count
@@db.transaction do
@@db['count'] || 0
end
end
def self.all
@@db.transaction do
@@db['all_ids'].map do |id|
@@db[id]
end
end
end
def self.find(id)
@@db.transaction do
item = @@db[id]
raise "Could not find Lamp##{id}!" if item.nil?
item
end
end
def to_s
@name.to_s.capitalize
end
end