Ruby’n Rails AASM or state machine

I wanted to use a state machine plugin for my Order model and found that ttilley-aasm was a good fit for me.

Here is how I installed it:

RAILS_ROOT/config/environmet.rb
config.gem 'ttilley-aasm', :source => 'http://gems.github.com', :lib => 'aasm'
# rake gems:install
# ./script/generate migration add_aasm_state_to_Order aasm_state:string
# rake db:migrate

And now how I test that it worked:

>> require 'aasm'
=> true
>> class Order
>> include AASM
>> aasm_initial_state :new
>> aasm_state :new
>> aasm_state :shipped
>> aasm_event :ship do
?> transitions :to => :shipped, :from => [:new]
>> end
>> end
=> #
>> Order.new.ship!
=> true

That worked now my Order class…

class Order < ActiveRecord::Base

include AASM
aasm_initial_state :in_progress

aasm_state :in_progress, :exit => :generate_order_number
aasm_state :shipped

aasm_event :ship do

transitions :to => :shipped, :from => [:in_progress], :if => :paid?

end

def generate_order_number; …; end
def paid?; …; end

end

That looks great!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: