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