Class: Spree::Calculator::PerItem

Inherits:
Spree::Calculator show all
Defined in:
app/models/spree/calculator/per_item.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Spree::Calculator

#available?, calculators, #description, register, #to_s

Class Method Details

.descriptionObject



10
11
12
# File 'app/models/spree/calculator/per_item.rb', line 10

def self.description
  Spree.t(:flat_rate_per_item)
end

Instance Method Details

#compute(object = nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'app/models/spree/calculator/per_item.rb', line 14

def compute(object=nil)
  return 0 if object.nil?
  self.preferred_amount * object.line_items.reduce(0) do |sum, value|
    if matching_products.blank? || matching_products.include?(value.product)
      value_to_add = value.quantity
    else
      value_to_add = 0
    end
    sum + value_to_add
  end
end

#matching_productsObject

Returns all products that match this calculator, but only if the calculator is attached to a promotion. If attached to a ShippingMethod, nil is returned.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'app/models/spree/calculator/per_item.rb', line 28

def matching_products
  # Regression check for #1596
  # Calculator::PerItem can be used in two cases.
  # The first is in a typical promotion, providing a discount per item of a particular item
  # The second is a ShippingMethod, where it applies to an entire order
  #
  # Shipping methods do not have promotions attached, but promotions do
  # Therefore we must check for promotions
  if self.calculable.respond_to?(:promotion)
    self.calculable.promotion.rules.map do |rule|
      rule.respond_to?(:products) ? rule.products : []
    end.flatten
  end
end