diff --git a/app/models/open_food_web/calculator/weight.rb b/app/models/open_food_web/calculator/weight.rb new file mode 100644 index 0000000000..dc1a35cf6b --- /dev/null +++ b/app/models/open_food_web/calculator/weight.rb @@ -0,0 +1,15 @@ +module OpenFoodWeb + class Calculator::Weight < Spree::Calculator + preference :per_kg, :decimal, :default => 0.0 + attr_accessible :preferred_per_kg + + def self.description + "Weight (per kg)" + end + + def compute(object) + total_weight = object.line_items.inject(0) { |sum, li| sum+li.variant.weight } + total_weight * self.preferred_per_kg + end + end +end diff --git a/config/application.rb b/config/application.rb index e6c3c3d81e..ef57eb64a2 100644 --- a/config/application.rb +++ b/config/application.rb @@ -27,6 +27,7 @@ module Openfoodweb # Register Spree calculators initializer "spree.register.calculators" do |app| app.config.spree.calculators.shipping_methods << OpenFoodWeb::Calculator::Itemwise + app.config.spree.calculators.shipping_methods << OpenFoodWeb::Calculator::Weight end diff --git a/spec/models/calculator/weight_spec.rb b/spec/models/calculator/weight_spec.rb new file mode 100644 index 0000000000..246f748cd6 --- /dev/null +++ b/spec/models/calculator/weight_spec.rb @@ -0,0 +1,16 @@ +require 'spec_helper' + +describe OpenFoodWeb::Calculator::Weight do + it "computes shipping cost for an order by total weight" do + variant_1 = double(:variant, :weight => 10) + variant_2 = double(:variant, :weight => 20) + + line_item_1 = double(:line_item, :variant => variant_1) + line_item_2 = double(:line_item, :variant => variant_2) + + order = double(:order, :line_items => [line_item_1, line_item_2]) + + subject.set_preference(:per_kg, 10) + subject.compute(order).should == 300 + end +end