From 2b0f6b786584199c6831de240c4cfbbb6f87bd3c Mon Sep 17 00:00:00 2001 From: Rohan Mitchell Date: Thu, 13 Nov 2014 17:34:31 +1100 Subject: [PATCH] Add ProductProxy which wraps the product's variants in VariantProxys --- lib/open_food_network/product_proxy.rb | 18 +++++++++++++ .../open_food_network/product_proxy_spec.rb | 27 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 lib/open_food_network/product_proxy.rb create mode 100644 spec/lib/open_food_network/product_proxy_spec.rb diff --git a/lib/open_food_network/product_proxy.rb b/lib/open_food_network/product_proxy.rb new file mode 100644 index 0000000000..e7f06f0019 --- /dev/null +++ b/lib/open_food_network/product_proxy.rb @@ -0,0 +1,18 @@ +module OpenFoodNetwork + class ProductProxy + instance_methods.each { |m| undef_method m unless m =~ /(^__|^send$|^object_id$)/ } + + def initialize(product, hub) + @product = product + @hub = hub + end + + def variants + @product.variants.map { |v| VariantProxy.new(v, @hub) } + end + + def method_missing(name, *args, &block) + @product.send(name, *args, &block) + end + end +end diff --git a/spec/lib/open_food_network/product_proxy_spec.rb b/spec/lib/open_food_network/product_proxy_spec.rb new file mode 100644 index 0000000000..e8a8565949 --- /dev/null +++ b/spec/lib/open_food_network/product_proxy_spec.rb @@ -0,0 +1,27 @@ +require 'open_food_network/product_proxy' +require 'open_food_network/variant_proxy' + +module OpenFoodNetwork + describe ProductProxy do + let(:hub) { double(:hub) } + let(:p) { double(:product, name: 'name') } + let(:pp) { ProductProxy.new(p, hub) } + + describe "delegating calls to proxied product" do + it "delegates name" do + pp.name.should == 'name' + end + end + + describe "fetching the variants" do + let(:v1) { double(:variant) } + let(:v2) { double(:variant) } + let(:p) { double(:product, variants: [v1, v2]) } + + it "returns variants wrapped in VariantProxy" do + # #class is proxied too, so we test that it worked by #object_id + pp.variants.map(&:object_id).sort.should_not == [v1.object_id, v2.object_id].sort + end + end + end +end