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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
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.rbindex 86a6c04295..0c820701cc 100644--- a/core/app/models/spree/product.rb+++ b/core/app/models/spree/product.rb@@ -90,6 +90,10 @@ module Spreeafter_save :reset_nested_changesafter_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: :updatebefore_validation :validate_master@@ -127,6 +131,13 @@ module Spreealias 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/259def purchasable?variants_including_master.any?(&:purchasable?)@@ -468,5 +479,11 @@ module Spreeerrors.add(:discontinue_on, :invalid_date_range)endend++ 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+ endendenddiff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rbindex 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 doexpect(latest_slug).not_to be_nilendend++ 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+ endendcontext 'properties' do