Class: Spree::Stock::Quantifier

Inherits:
Object
  • Object
show all
Defined in:
app/models/spree/stock/quantifier.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(variant, stock_location_or_id = nil) ⇒ Quantifier

Returns a new instance of Quantifier.

Parameters:

  • variant (Variant)

    The variant to check inventory for.

  • stock_location_or_id (StockLocation, Integer) (defaults to: nil)

    The stock_location or stock location ID to check inventory in. If unspecified it will check inventory in all available StockLocations



12
13
14
15
16
17
18
19
20
21
22
# File 'app/models/spree/stock/quantifier.rb', line 12

def initialize(variant, stock_location_or_id = nil)
  @variant = variant
  @stock_items = variant.stock_items.select do |stock_item|
    if stock_location_or_id
      stock_item.stock_location == stock_location_or_id ||
        stock_item.stock_location_id == stock_location_or_id
    else
      stock_item.stock_location.active?
    end
  end
end

Instance Attribute Details

#stock_itemsObject (readonly)

Returns the value of attribute stock_items.



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

def stock_items
  @stock_items
end

Instance Method Details

#backorderable?Boolean

Checks if any of its stock items are backorderable.

Returns:

  • (Boolean)

    true if any stock items are backorderable



39
40
41
# File 'app/models/spree/stock/quantifier.rb', line 39

def backorderable?
  stock_items.any?(&:backorderable)
end

#can_supply?(required) ⇒ Boolean

Checks if it is possible to supply a given number of units.

Parameters:

  • required (Fixnum)

    the number of required stock units

Returns:

  • (Boolean)

    true if we have the required amount on hand or the variant is backorderable, otherwise false



48
49
50
# File 'app/models/spree/stock/quantifier.rb', line 48

def can_supply?(required)
  total_on_hand >= required || backorderable?
end

#total_on_handFixnum

Returns the total number of inventory units on hand for the variant.

Returns:

  • (Fixnum)

    number of inventory units on hand, or infinity if inventory is not tracked on the variant.



28
29
30
31
32
33
34
# File 'app/models/spree/stock/quantifier.rb', line 28

def total_on_hand
  if @variant.should_track_inventory?
    stock_items.sum(&:count_on_hand)
  else
    Float::INFINITY
  end
end