Skip to content

Commit 0524dcd

Browse files
committed
Refactor Quantifier initialization
This is propedeutic for the following commit.
1 parent 67e609b commit 0524dcd

File tree

2 files changed

+25
-17
lines changed

2 files changed

+25
-17
lines changed

core/app/models/spree/stock/quantifier.rb

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,16 @@ class Quantifier
1111
# If unspecified it will check inventory in all available StockLocations
1212
def initialize(variant, stock_location_or_id = nil)
1313
@variant = variant
14-
@stock_items = variant.stock_items.select do |stock_item|
15-
if stock_location_or_id
16-
stock_item.stock_location == stock_location_or_id ||
17-
stock_item.stock_location_id == stock_location_or_id
18-
else
19-
stock_item.stock_location.active?
20-
end
21-
end
14+
@stock_location_or_id = stock_location_or_id
15+
@stock_items = variant_stock_items
2216
end
2317

2418
# Returns the total number of inventory units on hand for the variant.
2519
#
2620
# @return [Fixnum] number of inventory units on hand, or infinity if
2721
# inventory is not tracked on the variant.
2822
def total_on_hand
29-
if @variant.should_track_inventory?
23+
if variant.should_track_inventory?
3024
stock_items.sum(&:count_on_hand)
3125
else
3226
Float::INFINITY
@@ -48,6 +42,21 @@ def backorderable?
4842
def can_supply?(required)
4943
total_on_hand >= required || backorderable?
5044
end
45+
46+
private
47+
48+
attr_reader :variant, :stock_location_or_id
49+
50+
def variant_stock_items
51+
variant.stock_items.select do |stock_item|
52+
if stock_location_or_id
53+
stock_item.stock_location == stock_location_or_id ||
54+
stock_item.stock_location_id == stock_location_or_id
55+
else
56+
stock_item.stock_location.active?
57+
end
58+
end
59+
end
5160
end
5261
end
5362
end

core/spec/models/spree/stock/quantifier_spec.rb

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@
22

33
require 'rails_helper'
44

5-
RSpec.shared_examples_for 'unlimited supply' do
6-
it 'can_supply? any amount' do
7-
expect(subject.can_supply?(1)).to eq true
8-
expect(subject.can_supply?(101)).to eq true
9-
expect(subject.can_supply?(100_001)).to eq true
10-
end
11-
end
12-
135
module Spree
146
module Stock
157
RSpec.describe Quantifier, type: :model do
8+
shared_examples_for 'unlimited supply' do
9+
it 'can_supply? any amount' do
10+
expect(subject.can_supply?(1)).to eq true
11+
expect(subject.can_supply?(101)).to eq true
12+
expect(subject.can_supply?(100_001)).to eq true
13+
end
14+
end
1615
let(:target_stock_location) { nil }
1716
let!(:stock_location) { create :stock_location_with_items }
1817
let!(:stock_item) { stock_location.stock_items.order(:id).first }

0 commit comments

Comments
 (0)