Fetch indexed variant overrides in one go

This commit is contained in:
Rohan Mitchell
2015-06-18 15:03:24 +10:00
parent dd2f6d6430
commit aa0a031fa0
4 changed files with 20 additions and 3 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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)