-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitem.rb
82 lines (70 loc) · 2.53 KB
/
item.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
class Item
attr_accessor :item_name, :item_cat, :item_loc, :item_quant, :item_price, :item_desc
#create a new Item object
def initialize(item_name,item_cat,item_loc,item_quant,item_price,item_desc)
@item_name = item_name.downcase
@item_cat = item_cat.to_i
@item_loc = item_loc.to_i
@item_quant = item_quant
@item_price = item_price
@item_desc = item_desc
end
#insert item object into the database
def insert
attributes = []
instance_variables.each { |i|
attributes << i.to_s.delete("@")
}
query_components_array = []
attributes.each { |x|
value = self.send(x)
if value.is_a?(Integer)
query_components_array << "#{value}"
else
query_components_array << "'#{value}'"
end
}
query_string = query_components_array.join(", ")
puts query_string
DATABASE.execute("INSERT INTO items (name, category, location, quantity, cost, description) VALUES (#{query_string})")
puts "Inserted successfully!"
end
#delete item by id or name from database
def self.delete(value)
if value.is_a?(Integer)
DATABASE.execute("DELETE FROM items WHERE id = #{value}")
else
DATABASE.execute("DELETE FROM items WHERE name = '#{value}'")
end
end
#list all items with name and ids only
def self.list_items
DATABASE.execute("SELECT id, name FROM items")
end
#list all items including all fields
def self.list_items_details
DATABASE.execute("SELECT * FROM items")
end
#fetch all item details by id, name, category, location
def self.fetch_item_by(input,num)
if num == 1
DATABASE.execute("SELECT * FROM items WHERE id = #{input}")
elsif num == 2
DATABASE.execute("SELECT * FROM items WHERE name = '#{input}'")
elsif num == 3
DATABASE.execute("SELECT * FROM items WHERE category = '#{input}'")
else
DATABASE.execute("SELECT * FROM items WHERE location = '#{input}'")
end
end
#edit all item details by id or name
def self.edit(item_name,item_cat,item_loc,item_quant,item_price,item_desc,input)
if input.is_a?(Integer)
DATABASE.execute("UPDATE items SET name = '#{item_name}', category = '#{item_cat}', location = '#{item_loc}', quantity = #{item_quant},
cost = #{item_price}, description = '#{item_desc}' WHERE id = #{input}")
else
DATABASE.execute("UPDATE items SET name = '#{item_name}', category = '#{item_cat}', location = '#{item_loc}', quantity = #{item_quant},
cost = #{item_price}, description = '#{item_desc}' WHERE name = '#{input}'")
end
end
end