Class: Spree::Calculator

Inherits:
Base
  • Object
show all
Includes:
Preferences::Persistable
Defined in:
app/models/spree/calculator.rb

Defined Under Namespace

Modules: Returns, Shipping Classes: DefaultTax, FlatFee, FlatRate

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

display_includes

Methods included from Spree::Core::Permalinks

#generate_permalink, #save_permalink

Class Method Details

.descriptionString

A description for this calculator in few words

Returns:

  • (String)

    A description for the calculator



51
52
53
# File 'app/models/spree/calculator.rb', line 51

def self.description
  model_name.human
end

Instance Method Details

#available?(_object) ⇒ Boolean

Returns:

  • (Boolean)


65
66
67
# File 'app/models/spree/calculator.rb', line 65

def available?(_object)
  true
end

#compute(computable) ⇒ BigDecimal, Numeric

Computes an amount based on the calculable and the computable parameter.

This method dynamically calls a compute_<computable> method based on the class of the computable parameter. Concrete calculator classes must implement the appropriate compute method for each computable type they support.

For example, if the computable is a Spree::LineItem, this will call compute_line_item(computable, …). If the computable is a Spree::Order, it will call compute_order(computable, …).

Examples:

Implementing a calculator for line items

class MyCalculator < Spree::Calculator
  def compute_line_item(line_item)
    line_item.amount * 0.1 # 10% of line item amount
  end
end

Parameters:

  • computable (Object)

    The object to compute the amount for (e.g., Spree::LineItem, Spree::Order, Spree::Shipment, Spree::ShippingRate)

  • ... (args, kwargs)

    Additional arguments passed to the specific compute method

Returns:

  • (BigDecimal, Numeric)

    The computed amount

Raises:

  • (NotImplementedError)

    If the calculator doesn’t implement the required compute method

See Also:



37
38
39
40
41
42
43
44
45
46
47
# File 'app/models/spree/calculator.rb', line 37

def compute(computable, ...)
  # Spree::LineItem -> :compute_line_item
  computable_name = computable.class.name.demodulize.underscore
  method_name = :"compute_#{computable_name}"
  calculator_class = self.class
  if respond_to?(method_name)
    send(method_name, computable, ...)
  else
    raise NotImplementedError, "Please implement '#{method_name}(#{computable_name})' in your calculator: #{calculator_class.name}"
  end
end

#descriptionObject



61
62
63
# File 'app/models/spree/calculator.rb', line 61

def description
  self.class.description
end

#to_sObject



57
58
59
# File 'app/models/spree/calculator.rb', line 57

def to_s
  self.class.name.titleize.gsub("Calculator/", "")
end