Class: ProductAPI

Inherits:
Object
  • Object
show all
Extended by:
FileStorageModule
Defined in:
lib/ProductAPI.rb

Constant Summary collapse

@@file_path =
File.join(File.dirname(caller[0]), "/FileStorage/products.log")

Class Method Summary collapse

Methods included from FileStorageModule

add_line, read_file, remove_line, update_line

Class Method Details

.add(product) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/ProductAPI.rb', line 18

def self.add(product)
  @@list ||= Array.new
  product[:id] = max_id_value + 1
  puts "ProductAPI#add: Creating a product with these details: #{product}"
  @@list.push(product)
  add_line(@@file_path, product)
end

.delete(id) ⇒ Object



59
60
61
62
63
# File 'lib/ProductAPI.rb', line 59

def self.delete(id)
  puts "ProductAPI#delete: Deleting product id#{id}"
  @@list -= [search_id(id)]
  remove_line(@@file_path, search_id(id))
end

.get_listObject



14
15
16
# File 'lib/ProductAPI.rb', line 14

def self.get_list
  @@list ||= Array.new
end

.search(key, value) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/ProductAPI.rb', line 26

def self.search(key, value)
  if(key==:id || key==:quantity || key==:price)
    value = value.to_i
  end
  @@list.each do |product|
    return product if product[key] == value
  end
  return nil
end

.search_id(id) ⇒ Object



36
37
38
# File 'lib/ProductAPI.rb', line 36

def self.search_id(id)
  search(:id, id)
end

.seedObject



10
11
12
# File 'lib/ProductAPI.rb', line 10

def self.seed
  @@list = read_file(@@file_path)
end

.update(id, key, value) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ProductAPI.rb', line 40

def self.update(id, key, value)
  unless(key==:name || key==:color || key==:price || key==:quantity)
    puts "Invalid command. Cannot update #{key} field."
    return
  end
  if(key==:quantity || key==:price)
    value = value.to_i
  end
  old_product = search_id(id).clone
  @@list = @@list.map do |product|
    if product[:id] == id
      product[key] = value
      puts "ProductAPI#update: Updating product id#{id} with these details: #{key}: #{value}"
      update_line(@@file_path, old_product, product)
    end
      product
  end
end