Posts Tagged ‘aasm’

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!