Skip to content

Commit

Permalink
Refactor Stock Quantifier to use Enumerable
Browse files Browse the repository at this point in the history
This allows a developer to preload stock items and stock location,
removing many, many n+1 queries to the database.
  • Loading branch information
mamhoff committed Mar 3, 2022
1 parent 0ac2ee7 commit 5fefd82
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions core/app/models/spree/stock/quantifier.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ class Quantifier
# @param [StockLocation, Integer] stock_location The stock_location to check inventory in. If unspecified it will check inventory in all available StockLocations
def initialize(variant, stock_location = nil)
@variant = variant
@stock_items = Spree::StockItem.where(variant_id: variant)
if stock_location
@stock_items.where!(stock_location: stock_location)
else
@stock_items.joins!(:stock_location).merge!(Spree::StockLocation.active)
@stock_items = variant.stock_items.select do |stock_item|
if stock_location
stock_item.stock_location == stock_location
else
stock_item.stock_location.active?
end
end
end

Expand All @@ -23,7 +24,7 @@ def initialize(variant, stock_location = nil)
# inventory is not tracked on the variant.
def total_on_hand
if @variant.should_track_inventory?
stock_items.sum(:count_on_hand)
stock_items.map(&:count_on_hand).sum
else
Float::INFINITY
end
Expand Down

0 comments on commit 5fefd82

Please sign in to comment.