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.

Expire variants cache when changing position of master variant images (#12096)

Damian Legawiecee43c5382725
diff --git a/core/app/models/spree/image.rb b/core/app/models/spree/image.rb
index 0c28fb296f..a7749a57b4 100644
--- a/core/app/models/spree/image.rb
+++ b/core/app/models/spree/image.rb
@@ -4,6 +4,8 @@ module Spree
include Rails.application.routes.url_helpers
include Spree::ImageMethods
+ after_commit :touch_product_variants, if: :should_touch_product_variants?, on: :update
+
# In Rails 5.x class constants are being undefined/redefined during the code reloading process
# in a rails development environment, after which the actual ruby objects stored in those class constants
# are no longer equal (subclass == self) what causes error ActiveRecord::SubclassNotFound
@@ -51,5 +53,20 @@ module Spree
def plp_url
generate_url(size: self.class.styles[:plp_and_carousel])
end
+
+ private
+
+ def touch_product_variants
+ viewable.product.variants.touch_all
+ end
+
+ def should_touch_product_variants?
+ return false unless viewable.is_a?(Spree::Variant)
+ return false unless viewable.is_master?
+ return false unless viewable.product.has_variants?
+ return false unless saved_change_to_position?
+
+ true
+ end
end
end
diff --git a/core/spec/models/spree/image_spec.rb b/core/spec/models/spree/image_spec.rb
index 9947008f3b..c401035841 100644
--- a/core/spec/models/spree/image_spec.rb
+++ b/core/spec/models/spree/image_spec.rb
@@ -48,4 +48,32 @@ describe Spree::Image, type: :model do
expect(res[:size]).to eq described_class.styles[random_style_name]
end
end
+
+ context 'cache expiration' do
+ let!(:image) { create(:image, position: 1, viewable: viewable) }
+ let!(:image_2) { create(:image, position: 2, viewable: viewable) }
+
+ describe 'update position' do
+ let(:product) { create(:product) }
+ let!(:variants) { create_list(:variant, 2, product: product) }
+
+ context 'when viewable is a master variant' do
+ let(:viewable) { product.master }
+
+ it 'touches product variants' do
+ expect(image).to receive(:touch_product_variants)
+ image.set_list_position(2)
+ end
+ end
+
+ context 'when viewable is a variant' do
+ let(:viewable) { variants.first }
+
+ it 'does not touch product variants' do
+ expect(image).not_to receive(:touch_product_variants)
+ image.set_list_position(2)
+ end
+ end
+ end
+ end
end