Spree Commerce

Try It Now

Polymorphic Caclulators

Posted on August 13, 2009 by Sean Schofield

There has been significant refactoring to the implementation of calculators. Calculators are now polymorphic and belong to calculable. This will have a non trivial impact on your existing store configuration. After upgrading to Spree 0.9.0 you are likely going to have to make several manual adjustments to the existing tax and shipping configurations. Ultimately we feel this is outweighed by the superior design of the new calculator system which will allow for a more modular design.

WARNING Many of the existing calculator extensions are not yet updated to support Spree 0.9.0. Please check the extension registry to see which versions are supported. Our goal is to backport most of the useful calculators shortly after the release.

All calculators need to implement the following method

def compute(something=nil)

The calculator is passed an optional "target" on which to base their calculation. This method is expected to return a single numeric value when the calculation is complete. A value of nil should be returned in the event that a charge is not applicable.

Calculators are also configurable thorugh Spree’s flexible preference system. Default values for the preferences are configured through the class definition. For example, the flat rate calculator class definition specifies an amount with a default value of 0.

class Calculator::FlatRate < Calculator
preference :amount, :decimal, :default => 0

Spree now contains a standard mechanism by which calculator preferences can be editied. The screenshot below shows how the amounts for the flat rate calculator are now editable directly in the admin interface.