diff --git a/app/models/spree/variant_decorator.rb b/app/models/spree/variant_decorator.rb index 33e7f5bffd..36a4d0e45a 100644 --- a/app/models/spree/variant_decorator.rb +++ b/app/models/spree/variant_decorator.rb @@ -1,5 +1,6 @@ require 'open_food_network/enterprise_fee_calculator' require 'open_food_network/variant_and_line_item_naming' +require 'open_food_network/products_cache' Spree::Variant.class_eval do # Remove method From Spree, so method from the naming module is used instead @@ -24,6 +25,18 @@ Spree::Variant.class_eval do before_validation :update_weight_from_unit_value, if: -> v { v.product.present? } after_save :update_units + after_save :refresh_products_cache + around_destroy :refresh_products_cache_from_destroy + + def refresh_products_cache + OpenFoodNetwork::ProductsCache.variant_changed self + end + + def refresh_products_cache_from_destroy + OpenFoodNetwork::ProductsCache.variant_destroyed(self) { yield } + end + + scope :with_order_cycles_inner, joins(exchanges: :order_cycle) diff --git a/spec/models/spree/variant_spec.rb b/spec/models/spree/variant_spec.rb index cd6bfc1bd3..73789e62c2 100644 --- a/spec/models/spree/variant_spec.rb +++ b/spec/models/spree/variant_spec.rb @@ -1,5 +1,6 @@ require 'spec_helper' require 'open_food_network/option_value_namer' +require 'open_food_network/products_cache' module Spree describe Variant do @@ -112,6 +113,21 @@ module Spree end end + describe "callbacks" do + let(:variant) { create(:variant) } + + it "refreshes the products cache on save" do + expect(OpenFoodNetwork::ProductsCache).to receive(:variant_changed).with(variant) + variant.sku = 'abc123' + variant.save + end + + it "refreshes the products cache on destroy" do + expect(OpenFoodNetwork::ProductsCache).to receive(:variant_destroyed).with(variant) + variant.destroy + end + end + describe "indexing variants by id" do let!(:v1) { create(:variant) } let!(:v2) { create(:variant) }