Class: Warehouse::List

Inherits:
Object
  • Object
show all
Defined in:
lib/warehouse/list.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(items = nil) ⇒ List

Returns a new instance of List.



21
22
23
# File 'lib/warehouse/list.rb', line 21

def initialize(items=nil)
  self.items = (items || [])
end

Instance Attribute Details

#itemsObject

Returns the value of attribute items.



2
3
4
# File 'lib/warehouse/list.rb', line 2

def items
  @items
end

Class Method Details

.noneObject



16
17
18
# File 'lib/warehouse/list.rb', line 16

def none
  new
end

Instance Method Details

#*(qty) ⇒ Object

把料號 * 數量 (Clone List)



70
71
72
73
74
75
76
# File 'lib/warehouse/list.rb', line 70

def *(qty)
  Warehouse::List.new.tap do |list|
    items!.each do |item|
      list.items << item.deep_dup.tap { |i| i.qty = i.qty * qty }
    end
  end
end

#+(item) ⇒ Object

把料號加入到清單內 (Clone List)



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/warehouse/list.rb', line 53

def +(item)
  case item
  when Warehouse::Item::Code, Warehouse::Item::Barcode
    add_item(item)
  when Warehouse::Item::Random
    # 隨機抽一個
    add_item(item.fetch!)
  when Warehouse::List
    list = deep_dup
    item.each do |target|
      list += target
    end
    list
  end
end

#deep_dupObject



78
79
80
# File 'lib/warehouse/list.rb', line 78

def deep_dup
  Warehouse::List.new(items.map { |item| item.deep_dup })
end

#find(code, type: nil) ⇒ Object

找到此清單底下料號 (同樣 object_id)



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/warehouse/list.rb', line 26

def find(code, type: nil)
  case type
  when :code
    items.detect { |item| item.code? && item.code == code }
  when :barcode
    items.detect { |item| item.barcode? && item.barcode == code }
  else
    items.detect do |item|
      (item.code? && item.code == code) || (item.barcode? && item.barcode == code)
    end
  end
end

#items!Object

解開隨機料號 (New List)



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/warehouse/list.rb', line 40

def items!
  list = Warehouse::List.new
  items.each do |item|
    extra_items = item.is_a?(Warehouse::Item::Random) ? item.fetch! : [ item ]

    extra_items.each do |item|
      list.items << item
    end
  end
  list
end

#to_aObject



91
92
93
# File 'lib/warehouse/list.rb', line 91

def to_a
  items.map(&:to_h)
end

#to_hObject



82
83
84
85
86
87
88
89
# File 'lib/warehouse/list.rb', line 82

def to_h
  items.map do |item|
    [
      (item.code? ? item.code : item.barcode),
      item.qty
    ]
  end.to_h
end