Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Reset product memoized data on reload and save

Bogusław Tolarzc26eb6840d20
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index 86a6c04295..0c820701cc 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -90,6 +90,10 @@ module Spree
after_save :reset_nested_changes
after_touch :touch_taxons
+ # reset cache on save inside trasaction and transaction commit
+ after_save :reset_memoized_data
+ after_commit :reset_memoized_data
+
before_validation :normalize_slug, on: :update
before_validation :validate_master
@@ -127,6 +131,13 @@ module Spree
alias master_images images
+ def reload
+ %w(total_on_hand taxonomy_ids taxon_and_ancestors category category default_variant_id tax_category default_variant).each do |v|
+ instance_variable_set(:"@#{v}", nil)
+ end
+ super
+ end
+
# Cant use short form block syntax due to https://github.com/Netflix/fast_jsonapi/issues/259
def purchasable?
variants_including_master.any?(&:purchasable?)
@@ -468,5 +479,11 @@ module Spree
errors.add(:discontinue_on, :invalid_date_range)
end
end
+
+ def reset_memoized_data
+ %w(total_on_hand taxonomy_ids taxon_and_ancestors category default_variant_id tax_category default_variant).each do |v|
+ instance_variable_set(:"@#{v}", nil)
+ end
+ end
end
end
diff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rb
index efb2d4bf9c..c50e8fbf45 100644
--- a/core/spec/models/spree/product_spec.rb
+++ b/core/spec/models/spree/product_spec.rb
@@ -317,6 +317,29 @@ describe Spree::Product, type: :model do
expect(latest_slug).not_to be_nil
end
end
+
+ context 'memoized data' do
+ let(:corrent_total_on_hand) { 5 }
+ let(:incorrent_total_on_hand) { 15 }
+
+ before do
+ product.stock_items.first.set_count_on_hand corrent_total_on_hand
+ product.instance_variable_set(:@total_on_hand, incorrent_total_on_hand)
+ end
+
+ it 'without action keeps data' do
+ expect(product.total_on_hand).to eq incorrent_total_on_hand
+ end
+
+ it 'resets memoized data after save' do
+ product.save
+ expect(product.total_on_hand).to eq corrent_total_on_hand
+ end
+
+ it 'resets memoized data reload' do
+ expect(product.reload.total_on_hand).to eq corrent_total_on_hand
+ end
+ end
end
context 'properties' do