Friday, March 16, 2007

Acts As State Machine plugin

I just finished reading Bruce Tate article, Crossing borders: Extensions in Rails (The anatomy of an acts_as plug-in), where he mentioned the acts_as_state_machine plugin for Rails. If you ever have model with known transition paths between different states then this plugin will be a great help to you.

Here is an article, The Complete Guide to Rails Plugins: Part 1, on Nuby on Rails showing how to install and create Rails plugin.

And finally, you can go to the acts_as_state_machine plugin's author blog, Acts As State Machine, to see where to download and how to use the plugin.

Here is my example of how to use the plugin to keep track of a light fixture with three state (off, low, and high).

# The Migration class for light
class CreateLights < ActiveRecord::Migration
def self.up
create_table :lights do |t|
t.column :name, :string
t.column :status, :string
end
end

def self.down
drop_table :lights
end
end

# The Model for light

# A simple transition for a light with three states, (off, low, high)
#
# +---------+ switch +---------+ switch +---------+
# | off |-------->| low |-------->| high |
# +---------+ +---------+ +---------+
# ^ |
# |_________________________________________|
#
class Light < ActiveRecord::Base
acts_as_state_machine :initial => :off, :column => 'status'

state :off
state :low
state :high

event :switch do
transitions :from => :off, :to => :low
transitions :from => :low, :to => :high
transitions :from => :high, :to => :off
end
end

-------------------------
Here is a sample run:

>> l = Light.create
=> ...
>> l.current_state
=> :off
>> l.switch!
=> nil
>> l.current_state
=> :low
>> l.switch!
=> nil
>> l.current_state
=> :high
>> l.switch!
=> nil
>> l.current_state
=> :off

7 comments:

Unknown said...

Sometimes the smallest and simlpest things help the most.

Thank you for posting this little tutorial.

dimaspriyanto said...

yes.. simple post, but i like it much.. easy to understand

Anonymous said...

I agree with the previous two commenters--this was a good example for the uninitiated. Simple, easy to follow. I'm recommending it.

Conrad said...

I am glad this post is useful to a few readers out there. This is the reason why I still keep this blog up even though I haven't update it for a long while. I don't work with Ruby anymore. I love the language but no one wants to pay me to do Ruby work. :( Have fun programming in Ruby.

Anonymous said...

Totally agree with the first three commenters, sometimes you get an idea looking at the simplest example out there. Thanks for this small snippet which helped me understand how to use AASM.

daze said...

great article -
thanks for contributing

Ravi Shrivastava said...

good one