Spree Commerce

Try It Now

New Availablity Check for Shipping Calculators

Posted on February 21, 2009 by Sean Schofield

Edge Spree now supports a new is_available? method for shipping calculators. This allows calculators to deny the availability of the associated shipping option based on the details of the order. I recently needed this for a client selling consumer electronics.

The requiremens were that for customers buying large screen televisions, freight shipping should be the only option. The freight shipping option should not be available for an order that does not include a television.

Here’s an example of code that I used in the base shipping calculator class of all the standard calculators.


<p>def available?(order)<br />
  special_categories = ShippingCategory.find(:all, :conditions =&gt; [&#8220;name IN (&#8216;TV&#8217;, &#8216;Medium Size TV&#8217;, &#8216;Oversized TV&#8217;)&#8221;])<br />
  order.line_items.each do |line_item|<br />
    product = line_item.variant.product<br />
    return false if special_categories.include?(product.shipping_category)<br />
  end<br />
  true<br />
end</p>

This code will make the shipping method unavailable if any of the line items in the order contains a television. Note how the calculator makes use of the Shipping Category in performing its check. This is optional. Shipping calculators can make their determination based on any aspect of the order, including its contents or the shipment address.