Spree Commerce

Try It Now

Restful Refactoring Complete

Posted on September 08, 2008 by Sean Schofield

That flood in your Github feed can only mean one thing. Yup, the second phase of restful refactoring is now complete. We may eventually discover a few minor areas that still need to be addressed but at this point we’re basically done with the refactoring.

One big change is that we have dropped the Cart and CartItem models. Customers still have a shopping cart (from their perspective) but beind the scenes they are editing an order in various states.

Speaking of states, we’ve now incorporated the concept of Finite State Machine (FSM) into several aspects of the logic. There is a FSM for modelling both orders and inventories. If you haven’t used the state_machine plugin, be sure to give it a try. This is a new plugin that is not to be confused with the very similar acts_as_state_machine which apparently is not under active development.

One benefit of the FSM is that it makes it much easier to modify the checkout process. Take the tax_calculator extension (which is part of the Spree core) as an example. The idea is to calculate the tax after the user chooses a shipping address. We can do this simply by adding the following code in the activate method of the extension.

<p>Order.class_eval do<br />
  include Spree::TaxCalculator<br />
  Order.state_machines[&#8216;state&#8217;].after_transition(:to =&gt; &#8216;payment&#8217;,<br />
    :do =&gt; lambda {|order| order.update_attribute(:tax_amount, order.calculate_tax)})<br />

It should also be relatively easy to add new steps to a checkout process this way. Its still possible that upgrading to a future version of Spree might break your extension, but its much less likely to happen with this type of customization.

Speaking of future versions of Spree, please keep in mind that Spree is still in active development. Its definitely ready for use in a production environment but the architecture is still in a bit of flux (as evidenced by this recent refactoring.) As we get more people contributing to Spree and more experience deploying Spree in real world environments, there are just some things that are worth “breaking” in order to make significant reductions in lines of code, etc.

Please keep in mind that one of the ultimate goals of the Spree project is to make it as easy as possible to upgrade to future versions of Spree. In the future, new versions of Spree will contain rake tasks, etc. to assist in migrating from a previous version. We also hope to include more detailed documentation on changes between versions and suggestions for how to design your application in order to minimize problems with future migrations.

Please report any problems to spree-user or the issue tracker.