diff --git a/app/models/variant_override.rb b/app/models/variant_override.rb index a552cb98bb..55afd99321 100644 --- a/app/models/variant_override.rb +++ b/app/models/variant_override.rb @@ -8,6 +8,12 @@ class VariantOverride < ActiveRecord::Base where(hub_id: hubs) } + def self.indexed(hub) + Hash[ + for_hubs(hub).map { |vo| [vo.variant, vo] } + ] + end + def self.price_for(hub, variant) self.for(hub, variant).andand.price end diff --git a/lib/open_food_network/scope_product_to_hub.rb b/lib/open_food_network/scope_product_to_hub.rb index 8c59feb3cc..d3e018f295 100644 --- a/lib/open_food_network/scope_product_to_hub.rb +++ b/lib/open_food_network/scope_product_to_hub.rb @@ -4,17 +4,19 @@ module OpenFoodNetwork class ScopeProductToHub def initialize(hub) @hub = hub + @variant_overrides = VariantOverride.indexed @hub end def scope(product) product.send :extend, OpenFoodNetwork::ScopeProductToHub::ScopeProductToHub product.instance_variable_set :@hub, @hub + product.instance_variable_set :@variant_overrides, @variant_overrides end module ScopeProductToHub def variants_distributed_by(order_cycle, distributor) - super.each { |v| ScopeVariantToHub.new(@hub).scope(v) } + super.each { |v| ScopeVariantToHub.new(@hub, @variant_overrides).scope(v) } end end end diff --git a/lib/open_food_network/scope_variant_to_hub.rb b/lib/open_food_network/scope_variant_to_hub.rb index d21f3ede1f..2cf79ee28d 100644 --- a/lib/open_food_network/scope_variant_to_hub.rb +++ b/lib/open_food_network/scope_variant_to_hub.rb @@ -1,13 +1,14 @@ module OpenFoodNetwork class ScopeVariantToHub - def initialize(hub) + def initialize(hub, variant_overrides=nil) @hub = hub + @variant_overrides = variant_overrides || VariantOverride.indexed(@hub) end def scope(variant) variant.send :extend, OpenFoodNetwork::ScopeVariantToHub::ScopeVariantToHub variant.instance_variable_set :@hub, @hub - variant.instance_variable_set :@variant_override, VariantOverride.send(:for, @hub, variant) + variant.instance_variable_set :@variant_override, @variant_overrides[variant] end diff --git a/spec/models/variant_override_spec.rb b/spec/models/variant_override_spec.rb index 3a6bd9b1df..e9f22a33be 100644 --- a/spec/models/variant_override_spec.rb +++ b/spec/models/variant_override_spec.rb @@ -14,8 +14,16 @@ describe VariantOverride do it "finds variant overrides for a set of hubs" do VariantOverride.for_hubs([hub1, hub2]).should match_array [vo1, vo2] end + + describe "fetching variant overrides indexed by variant" do + it "gets indexed variant overrides for one hub" do + VariantOverride.indexed(hub1).should == {v => vo1} + VariantOverride.indexed(hub2).should == {v => vo2} + end + end end + describe "looking up prices" do it "returns the numeric price when present" do VariantOverride.create!(variant: variant, hub: hub, price: 12.34)