From c98e44c5a1de6cd0b238e1dbcd09e7d2334cd388 Mon Sep 17 00:00:00 2001 From: Rohan Mitchell Date: Thu, 28 Jan 2016 16:00:55 +1100 Subject: [PATCH] Perform refresh of products cache on product change --- lib/open_food_network/products_cache.rb | 11 +++++++---- .../open_food_network/products_cache_spec.rb | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/open_food_network/products_cache.rb b/lib/open_food_network/products_cache.rb index eae1a62d15..66a2c8b164 100644 --- a/lib/open_food_network/products_cache.rb +++ b/lib/open_food_network/products_cache.rb @@ -4,14 +4,14 @@ module OpenFoodNetwork # the products cache. class ProductsCache def self.variant_changed(variant) - exchanges_featuring_variant(variant).each do |exchange| + exchanges_featuring_variants(variant).each do |exchange| refresh_cache exchange.receiver, exchange.order_cycle end end def self.variant_destroyed(variant, &block) - exchanges = exchanges_featuring_variant(variant).to_a + exchanges = exchanges_featuring_variants(variant).to_a block.call @@ -22,15 +22,18 @@ module OpenFoodNetwork def self.product_changed(product) + exchanges_featuring_variants(product.variants).each do |exchange| + refresh_cache exchange.receiver, exchange.order_cycle + end end private - def self.exchanges_featuring_variant(variant) + def self.exchanges_featuring_variants(variants) Exchange. outgoing. - with_variant(variant). + with_any_variant(variants). joins(:order_cycle). merge(OrderCycle.dated). merge(OrderCycle.not_closed) diff --git a/spec/lib/open_food_network/products_cache_spec.rb b/spec/lib/open_food_network/products_cache_spec.rb index afc54ae87b..d48f5e7d5c 100644 --- a/spec/lib/open_food_network/products_cache_spec.rb +++ b/spec/lib/open_food_network/products_cache_spec.rb @@ -70,6 +70,25 @@ module OpenFoodNetwork end end + describe "when a product changes" do + let(:product) { create(:simple_product) } + let(:v1) { create(:variant, product: product) } + let(:v2) { create(:variant, product: product) } + let(:d1) { create(:distributor_enterprise) } + let(:d2) { create(:distributor_enterprise) } + let(:oc) { create(:open_order_cycle) } + let!(:ex1) { create(:exchange, order_cycle: oc, sender: oc.coordinator, receiver: d1, variants: [v1]) } + let!(:ex2) { create(:exchange, order_cycle: oc, sender: oc.coordinator, receiver: d2, variants: [v1, v2]) } + + before { product.reload } + + it "refreshes the distribution each variant appears in, once each" do + expect(ProductsCache).to receive(:refresh_cache).with(d1, oc).once + expect(ProductsCache).to receive(:refresh_cache).with(d2, oc).once + ProductsCache.product_changed product + end + end + describe "refreshing the cache" do let(:distributor) { double(:distributor, id: 123) } let(:order_cycle) { double(:order_cycle, id: 456) }