Class: Stockr::Part

Inherits:
Object
  • Object
show all
Defined in:
lib/stockr/part.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, qty = 0, pr = 0) ⇒ Part

Returns a new instance of Part.



8
9
10
11
12
# File 'lib/stockr/part.rb', line 8

def initialize(name, qty = 0, pr = 0)
  @name = name.upcase
  @qty = qty.to_i
  self.price = pr
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/stockr/part.rb', line 6

def name
  @name
end

#priceObject

Returns the value of attribute price.



6
7
8
# File 'lib/stockr/part.rb', line 6

def price
  @price
end

#qtyObject

Returns the value of attribute qty.



6
7
8
# File 'lib/stockr/part.rb', line 6

def qty
  @qty
end

Class Method Details

.allObject



69
# File 'lib/stockr/part.rb', line 69

def self.all;      search('');    end

.create_or_increment(q, name, pr = 0) ⇒ Object



54
55
56
# File 'lib/stockr/part.rb', line 54

def self.create_or_increment(q, name, pr=0)
  find_or_create(q, name, pr, true)
end

.find_or_create(q, name, pr = 0, incr = false) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/stockr/part.rb', line 46

def self.find_or_create(q, name, pr=0, incr = false)
  part = search(name, true) || new(name)
  incr ? part.qty += q.to_i : part.qty = q.to_i
  part.price = pr
  part.save
  part
end

.list(txt = "*") ⇒ Object



71
72
73
# File 'lib/stockr/part.rb', line 71

def self.list(txt = "*")
  search(txt).map(&:facts) rescue []
end

.missingObject



75
76
77
# File 'lib/stockr/part.rb', line 75

def self.missing
  all.select { |p| p.qty <= 0 }
end

.search(txt, exact = false) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'lib/stockr/part.rb', line 58

def self.search(txt, exact = false)
  if res = Store.find(exact ? txt : "*#{txt}*")
    objs = res.map do |k, r|
      new(k, r["qty"], r["price"])
    end
    exact ? objs[0] : objs # FIXME: better way?
  else
    nil
  end
end

Instance Method Details

#factsObject



19
20
21
22
23
24
25
26
27
# File 'lib/stockr/part.rb', line 19

def facts
  out = "#{qty}x #{name}"
  if price && !price.zero?
    out << ("." * (50 - out.size))
    out << "$ %.3f" % price
    out << " ($ %.3f)" % (price * qty) if qty != 1
  end
  out
end

#price_totalObject



38
39
40
# File 'lib/stockr/part.rb', line 38

def price_total
  price * qty
end

#saveObject



14
15
16
17
# File 'lib/stockr/part.rb', line 14

def save
  return false unless name && !name.empty?
  Store.write(name, { :qty => qty, :price => price })
end

#to_jsonObject



42
43
44
# File 'lib/stockr/part.rb', line 42

def to_json
  "{name: '#{name}', qty: '#{qty}', price: '%.3f', total_price: '%.3f'}" % [price, price_total]
end