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)


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

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

  @quantities = quantities
end

Instance Attribute Details

#quantitiesObject (readonly)

Returns the value of attribute quantities.



6
7
8
# File 'app/models/spree/stock_quantities.rb', line 6

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.



52
53
54
55
56
57
58
# File 'app/models/spree/stock_quantities.rb', line 52

def &(other)
  combine_with(other) do |_variant, first, second|
    next unless first && second

    [first, second].min
  end
end

#+(other) ⇒ Spree::StockQuantities

Adds two StockQuantities together



35
36
37
38
39
# File 'app/models/spree/stock_quantities.rb', line 35

def +(other)
  combine_with(other) do |_variant, first, second|
    (first || 0) + (second || 0)
  end
end

#-(other) ⇒ Spree::StockQuantities

Subtracts another StockQuantities from this one



43
44
45
46
47
# File 'app/models/spree/stock_quantities.rb', line 43

def -(other)
  combine_with(other) do |_variant, first, second|
    (first || 0) - (second || 0)
  end
end

#==(other) ⇒ Object



66
67
68
69
# File 'app/models/spree/stock_quantities.rb', line 66

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

#[](variant) ⇒ Integer

Returns the quantity of variant.

Parameters:

Returns:

  • (Integer)

    the quantity of variant



24
25
26
# File 'app/models/spree/stock_quantities.rb', line 24

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

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

Yields:

  • (variant, quantity)


18
19
20
# File 'app/models/spree/stock_quantities.rb', line 18

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

#empty?true, false

A StockQuantities is empty if all variants have zero quantity

Returns:

  • (true, false)


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

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

#variantsArray<Spree::Variant>

Returns the variants being tracked.

Returns:



29
30
31
# File 'app/models/spree/stock_quantities.rb', line 29

def variants
  @quantities.keys.uniq
end