Description

State machines make it dead-simple to manage the behavior of a class. Too often,
the state of an object is kept by creating multiple boolean attributes and
deciding how to behave based on the values. This can become cumbersome and
difficult to maintain when the complexity of your class starts to increase.

state_machine simplifies this design by introducing the various parts of a real
state machine, including states, events, transitions, and callbacks. However,
the api is designed to be so simple you don't even need to know what a
state machine is :)

Examples of the usage patterns for some of the above features are shown below.
You can find much more detailed documentation in the actual API.

Usage

Example

Below is an example of many of the features offered by this plugin, including:

Initial states

Namespaced states

Transition callbacks

Conditional transitions

State-driven instance behavior

Customized state values

Parallel events

Path analysis

Class definition:

classVehicleattr_accessor:seatbelt_on,:time_used,:auto_shop_busystate_machine:state,:initial=>:parkeddobefore_transition:parked=>any-:parked,:do=>:put_on_seatbeltafter_transition:on=>:crash,:do=>:towafter_transition:on=>:repair,:do=>:fixafter_transitionany=>:parkeddo|vehicle,transition|vehicle.seatbelt_on=falseendafter_failure:on=>:ignite,:do=>:log_start_failurearound_transitiondo|vehicle,transition,block|start=Time.nowblock.callvehicle.time_used+=Time.now-startendevent:parkdotransition[:idling,:first_gear]=>:parkedendevent:ignitedotransition:stalled=>same,:parked=>:idlingendevent:idledotransition:first_gear=>:idlingendevent:shift_updotransition:idling=>:first_gear,:first_gear=>:second_gear,:second_gear=>:third_gearendevent:shift_downdotransition:third_gear=>:second_gear,:second_gear=>:first_gearendevent:crashdotransitionall-[:parked,:stalled]=>:stalled,:if=>lambda{|vehicle|!vehicle.passed_inspection?}endevent:repairdo# The first transition that matches the state and passes its conditions
# will be used
transition:stalled=>:parked,:unless=>:auto_shop_busytransition:stalled=>sameendstate:parkeddodefspeed0endendstate:idling,:first_geardodefspeed10endendstateall-[:parked,:stalled,:idling]dodefmoving?trueendendstate:parked,:stalled,:idlingdodefmoving?falseendendendstate_machine:alarm_state,:initial=>:active,:namespace=>'alarm'doevent:enabledotransitionall=>:activeendevent:disabledotransitionall=>:offendstate:active,:value=>1state:off,:value=>0enddefinitialize@seatbelt_on=false@time_used=0@auto_shop_busy=truesuper()# NOTE: This *must* be called, otherwise states won't get initialized
enddefput_on_seatbelt@seatbelt_on=trueenddefpassed_inspection?falseenddeftow# tow the vehicle
enddeffix# get the vehicle fixed by a mechanic
enddeflog_start_failure# log a failed attempt to start the vehicle
endend

Note the comment made on the initialize method in the class. In order for
state machine attributes to be properly initialized, super() must be called.
See StateMachine::MacroMethods for more information about this.

Using the above class as an example, you can interact with the state machine
like so:

Integrations

In addition to being able to define state machines on all Ruby classes, a set of
out-of-the-box integrations are available for some of the more popular Ruby
libraries. These integrations add library-specific behavior, allowing for state
machines to work more tightly with the conventions defined by those libraries.

The integrations currently available include:

ActiveModel classes

ActiveRecord models

DataMapper resources

Mongoid models

MongoMapper models

Sequel models

A brief overview of these integrations is described below.

ActiveModel

The ActiveModel integration is useful for both standalone usage and for providing
the base implementation for ORMs which implement the ActiveModel API. This
integration adds support for validation errors, dirty attribute tracking, and
observers. For example,

For more information about the various behaviors added for ActiveRecord state
machines, see StateMachine::Integrations::ActiveRecord.

DataMapper

Like the ActiveRecord integration, the DataMapper integration adds support for
database transactions, automatically saving the record, named scopes, Extlib-like
callbacks, validation errors, and observers. For example,

class Vehicle
include DataMapper::Resource
property :id, Serial
property :state, String
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition any => :parked do |transition|
self.seatbelt = 'off' # self is the record
end
around_transition :benchmark
event :ignite do
transition :parked => :idling
end
state :first_gear, :second_gear do
validates_presence_of :seatbelt_on
end
end
def put_on_seatbelt
...
end
def benchmark
...
yield
...
end
end
class VehicleObserver
include DataMapper::Observer
observe Vehicle
# Callback for :ignite event *before* the transition is performed
before_transition :on => :ignite do |transition|
# log message (self is the record)
end
# Generic transition callback *after* the transition is performed
after_transition do |transition|
Audit.log(self, transition) # self is the record
end
around_transition do |transition, block|
# mark start time
block.call
# mark stop time
end
# Generic callback after the transition fails to perform
after_transition_failure do |transition|
Audit.log(self, transition) # self is the record
end
end

Note that the DataMapper::Observer integration is optional and only available
when the dm-observer library is installed.

For more information about the various behaviors added for DataMapper state
machines, see StateMachine::Integrations::DataMapper.

Mongoid

The Mongoid integration adds support for automatically saving the record,
basic scopes, validation errors, and observers. For example,

For more information about the various behaviors added for Sequel state
machines, see StateMachine::Integrations::Sequel.

Additional Topics

Explicit vs. Implicit Event Transitions

Every event defined for a state machine generates an instance method on the
class that allows the event to be explicitly triggered. Most of the examples in
the state_machine documentation use this technique. However, with some types of
integrations, like ActiveRecord, you can also implicitly fire events by
setting a special attribute on the instance.

Suppose you're using the ActiveRecord integration and the following model is
defined:

This is referred to as an explicit event transition. The same behavior can
also be achieved implicitly by setting the state event attribute and invoking
the action associated with the state machine. For example:

You could even use numbers as your state / event names. The important thing
to keep in mind is that the type being used for referencing states / events in
your machine definition must be consistent. If you're using Symbols, then
all states / events must use Symbols. Otherwise you'll encounter the following
error:

classVehiclestate_machinedoevent:ignitedotransition:parked=>'idling'endendend# => ArgumentError: "idling" state defined as String, :parked defined as Symbol; all states must be consistent

There is an exception to this rule. The consistency is only required within
the definition itself. However, when the machine's helper methods are called
with input from external sources, such as a web form, state_machine will map
that input to a String / Symbol. For example:

Note that none of this actually has to do with the type of the value that
gets stored. By default, all state values are assumed to be string -- regardless
of whether the state names are symbols or strings. If you want to store states
as symbols instead you'll have to be explicit about it:

Syntax flexibility

Although state_machine introduces a simplified syntax, it still remains
backwards compatible with previous versions and other state-related libraries by
providing some flexibility around how transitions are defined. See below for an
overview of these syntaxes.

Verbose syntax

In general, it's recommended that state machines use the implicit syntax for
transitions. However, you can be a little more explicit and verbose about
transitions by using the :from, :except_from, :to,
and :except_to options.

For example, transitions and callbacks can be defined like so:

classVehiclestate_machine:initial=>:parkeddobefore_transition:from=>:parked,:except_to=>:parked,:do=>:put_on_seatbeltafter_transition:to=>:parkeddo|transition|self.seatbelt='off'# self is the record
endevent:ignitedotransition:from=>:parked,:to=>:idlingendendend

Transition context

Some flexibility is provided around the context in which transitions can be
defined. In almost all examples throughout the documentation, transitions are
defined within the context of an event. If you prefer to have state machines
defined in the context of a state either out of preference or in order to
easily migrate from a different library, you can do so as shown below:

In the above example, there's no need to specify the from state for each
transition since it's inferred from the context.

You can also define transitions completely outside the context of a particular
state / event. This may be useful in cases where you're building a state
machine from a data store instead of part of the class definition. See the
example below:

You can continue to define from states (when in the machine context) using
the all, any, and same helper methods

Static / Dynamic definitions

In most cases, the definition of a state machine is static. That is to say,
the states, events and possible transitions are known ahead of time even though
they may depend on data that's only known at runtime. For example, certain
transitions may only be available depending on an attribute on that object it's
being run on. All of the documentation in this library define static machines
like so:

However, there may be cases where the definition of a state machine is dynamic.
This means that you don't know the possible states or events for a machine until
runtime. For example, you may allow users in your application to manage the
state machine of a project or task in your system. This means that the list of
transitions (and their associated states / events) could be stored externally,
such as in a database. In a case like this, you can define dynamically-generated
state machines like so:

As you can see, state_machine provides enough flexibility for you to be able
to create new machine definitions on the fly based on an external source of
transitions.

Core Extensions

By default, state_machine extends the Ruby core with a state_machine method on
Class. All other parts of the library are confined within the StateMachine
namespace. While this isn't wholly necessary, it also doesn't have any performance
impact and makes it truly feel like an extension to the language. This is very
similar to the way that you'll find yaml, json, or other libraries adding a
simple method to all objects just by loading the library.

However, if you'd like to avoid having state_machine add this extension to the
Ruby core, you can do so like so:

Tools

Generating graphs

This library comes with built-in support for generating di-graphs based on the
events, states, and transitions defined for a state machine using GraphViz.
This requires that both the ruby-graphviz gem and graphviz library be
installed on the system.

Note that this will generate a different file for every state machine defined
in the class. The generated files will use an output filename of the format
#{class_name}_#{machine_name}.#{format}.

For examples of actual images generated using this task, see those under the
examples folder.

Interactive graphs

Jean Bovet's Visual Automata Simulator
is a great tool for "simulating, visualizing and transforming finite state
automata and Turing Machines". It can help in the creation of states and events
for your models. It is cross-platform, written in Java.

Generating documentation

If you use YARD to generate documentation for your projects, state_machine can
be enabled to generate API docs for auto-generated methods from each state machine
definition as well as providing embedded visualizations.

See the generated API documentation under the examples folder to see what the
output looks like.

To enable the YARD integration, you'll need to add state_machine to the list of
YARD's plugins by editing the global YARD config:

~/.yard/config:

load_plugins: true
autoload_plugins:
- state_machine

Once enabled, simply generate your documentation like you normally do.

Note that this only works for Ruby 1.9+.

Web Frameworks

Ruby on Rails

Integrating state_machine into your Ruby on Rails application is straightforward
and provides a few additional features specific to the framework. To get
started, following the steps below.

Rake tasks

There is a special integration Rake task for generating state machines for
classes used in a Ruby on Rails application. This task will load the application
environment, meaning that it's unnecessary to specify the actual file to load.

For example,

rake state_machine:draw CLASS=Vehicle

If you are using this library as a gem in Rails 2.x, the following must be added
to the end of your application's Rakefile in order for the above task to work:

require'tasks/state_machine'

Merb

Rake tasks

Like Ruby on Rails, there is a special integration Rake task for generating
state machines for classes used in a Merb application. This task will load the
application environment, meaning that it's unnecessary to specify the actual
files to load.