Class: Spree::StockQuantities

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
app/models/spree/stock_quantities.rb

Overview

A value object to hold a map of variants to their quantities

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(quantities = {}) ⇒ StockQuantities

Returns a new instance of StockQuantities

Parameters:

Raises:

  • (ArgumentError)


8
9
10
11
12
13
# File 'app/models/spree/stock_quantities.rb', line 8

def initialize(quantities = {})
  raise ArgumentError unless quantities.keys.all?{ |v| v.is_a?(Spree::Variant) }
  raise ArgumentError unless quantities.values.all?{ |v| v.is_a?(Numeric) }

  @quantities = quantities
end

Instance Attribute Details

#quantitiesObject (readonly)

Returns the value of attribute quantities



4
5
6
# File 'app/models/spree/stock_quantities.rb', line 4

def quantities
  @quantities
end

Instance Method Details

#&(other) ⇒ Spree::StockQuantities

Finds the intersection or common subset of two StockQuantities: the stock which exists in both StockQuantities.



50
51
52
53
54
55
# File 'app/models/spree/stock_quantities.rb', line 50

def &(other)
  combine_with(other) do |_variant, a, b|
    next unless a && b
    [a, b].min
  end
end

#+(other) ⇒ Spree::StockQuantities

Adds two StockQuantities together



33
34
35
36
37
# File 'app/models/spree/stock_quantities.rb', line 33

def +(other)
  combine_with(other) do |_variant, a, b|
    (a || 0) + (b || 0)
  end
end

#-(other) ⇒ Spree::StockQuantities

Subtracts another StockQuantities from this one



41
42
43
44
45
# File 'app/models/spree/stock_quantities.rb', line 41

def -(other)
  combine_with(other) do |_variant, a, b|
    (a || 0) - (b || 0)
  end
end

#==(other) ⇒ Object



63
64
65
66
# File 'app/models/spree/stock_quantities.rb', line 63

def ==(other)
  self.class == other.class &&
    quantities == other.quantities
end

#[](variant) ⇒ Integer

Returns the quantity of variant

Parameters:

Returns:

  • (Integer)

    the quantity of variant



22
23
24
# File 'app/models/spree/stock_quantities.rb', line 22

def [](variant)
  @quantities[variant]
end

#each {|variant, quantity| ... } ⇒ Object

Yields:

  • (variant, quantity)


16
17
18
# File 'app/models/spree/stock_quantities.rb', line 16

def each(&block)
  @quantities.each(&block)
end

#empty?true, false

A StockQuantities is empty if all variants have zero quantity

Returns:

  • (true, false)


59
60
61
# File 'app/models/spree/stock_quantities.rb', line 59

def empty?
  @quantities.values.all?(&:zero?)
end

#variantsArray<Spree::Variant>

Returns the variants being tracked

Returns:



27
28
29
# File 'app/models/spree/stock_quantities.rb', line 27

def variants
  @quantities.keys.uniq
end