Weight calculator will calculate against a single line item as well as an order

This commit is contained in:
Rohan Mitchell
2013-08-08 11:18:42 +10:00
parent a338c974f8
commit 239dd29511
2 changed files with 24 additions and 1 deletions

View File

@@ -8,8 +8,22 @@ module OpenFoodWeb
end
def compute(object)
total_weight = object.line_items.inject(0) { |sum, li| sum + ((li.variant.andand.weight || 0) * li.quantity) }
line_items = line_items_for object
total_weight = line_items.sum { |li| ((li.variant.andand.weight || 0) * li.quantity) }
total_weight * self.preferred_per_kg
end
private
def line_items_for(object)
if object.respond_to? :line_items
object.line_items
elsif object.respond_to?(:variant) && object.respond_to?(:quantity)
[object]
else
raise "Unknown object type: #{object.inspect}"
end
end
end
end

View File

@@ -15,4 +15,13 @@ describe OpenFoodWeb::Calculator::Weight do
subject.set_preference(:per_kg, 10)
subject.compute(order).should == (10*1 + 20*3) * 10
end
it "computes shipping cost for a line item" do
variant = double(:variant, :weight => 10)
line_item = double(:line_item, :variant => variant, :quantity => 2)
subject.set_preference(:per_kg, 10)
subject.compute(line_item).should == 10*2 * 10
end
end