metasploit-framework/lib/gemcache/ruby/1.9.1/gems/state_machine-1.1.2/README.md

1155 lines
32 KiB
Markdown
Raw Normal View History

Cutting over rails3 to master. This switches the Metasploit Framework to a Rails 3 backend. If you run into new problems (especially around Active Record or your postgresql gem) you should try first updating your Ruby installation to 1.9.3 and use a more recent 'pg' gem. If that fails, we'd love to see your bug report (just drop all the detail you can into an issue on GitHub). In the meantime, you can checkout the rails2 branch, which was branched from master immediately before this cutover. Squashed commit of the following: commit 5802ec851580341c6717dfea529027c12678d35f Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 23:30:12 2012 -0500 Enable MSF_BUNDLE_GEMS mode by default (set to N/F/0 to disable) commit 8102f98dce9eb0c73c4374e40dce09af7b51d060 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 23:30:03 2012 -0500 Add a method to expand win32 file paths commit bda6479d154cf75572dd5de8b66bfde661a55de9 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 18:53:44 2012 -0500 Fix 1.8.x compatibility commit 101ce4eb17bfdf755ef8c0a5198174668b6cd6fd Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 18:40:59 2012 -0500 Use verbose instead of stringio commit 5db467ffb593488285576d183b1662093e454b3e Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 18:30:06 2012 -0500 Hide the iconv warning, were stuck with it due to EBCDIC support commit 63b9cb20eb6a61daf4effb4c8d2761c16ff0c4e0 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 18:29:58 2012 -0500 Dont use GEM_HOME by default commit ca49271c22c314a4465fff934334df18c704cbc0 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 18:23:34 2012 -0500 Move Gemfile to root (there be dragons, lets find them) and catch failed bundler loads commit 34af04076a068e9f60c5526045ddbba5fca359fd Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 18:18:29 2012 -0500 Fallback to bundler when not running inside of a installer env commit ed1066a4f3f12fae7d4afc03eb1ab70ffe2f9cf3 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 16:26:55 2012 -0500 Remove a mess of gems that were not actually required commit 21290a73926809e9049a59359449168f740d13d2 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 15:59:10 2012 -0500 Hack around a gem() call that is well-intentioned but an obstacle in this case commit 8e414a8bfab9641c81088d22f73033be5b37a700 Author: Tod Beardsley <todb@metasploit.com> Date: Sun Apr 15 15:06:08 2012 -0500 Ruby, come on. Ducktype this. Please. Use interpolated strings to get the to_s behavior you don't get with just plussing. commit 0fa92c58750f8f84edbecfaab72cd2da5062743f Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 15:05:42 2012 -0500 Add new eventmachine/thin gems commit 819d5e7d45e0a16741d3852df3ed110b4d7abc44 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 15:01:18 2012 -0500 Purge (reimport in a second) commit ea6f3f6c434537ca15b6c6674e31081e27ce7f86 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 14:54:42 2012 -0500 Cleanup uncessary .so files (ext vs lib) commit d219330a3cc563e9da9f01fade016c9ed8cda21c Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 14:53:02 2012 -0500 PG gems built against the older installation environment commit d6e590cfa331ae7b25313ff1471c6148a6b36f3b Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 14:06:35 2012 -0500 Rename to include the version commit a893de222b97ce1222a55324f1811b0262aae2d0 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 13:56:47 2012 -0500 Detect older installation environments and load the arch-lib directories into the search path commit 6444bba0a421921e2ebe2df2323277a586f9736f Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 13:49:25 2012 -0500 Merge in windows gems commit 95efbcfde220917bc7ee08e6083d7b383240d185 Author: Tod Beardsley <todb@metasploit.com> Date: Sun Apr 15 13:49:33 2012 -0500 Report_vuln shouldn't use :include in finder find_or_create_by doesn't take :include as a param. commit c5f99eb87f0874ef7d32fa42828841c9a714b787 Author: David Maloney <DMaloney@rapid7.com> Date: Sun Apr 15 12:44:09 2012 -0500 One more msised Mdm namespace issue commit 2184e2bbc3dd9b0993e8f21d2811a65a0c694d68 Author: David Maloney <DMaloney@rapid7.com> Date: Sun Apr 15 12:33:41 2012 -0500 Fixes some mroe Mdm namespace confusion Fixes #6626 commit 10cee17f391f398bb2be3409137ff7348c7a66ee Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 03:40:44 2012 -0500 Add robots gem (required by webscan) commit 327e674c83850101364c9cca8f8d16da1de3dfb5 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 03:39:05 2012 -0500 Fix missing error checks commit a5a24641866e47e611d7636a3f19ba3b3ed10ac5 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 01:15:37 2012 -0500 Reorder requires and add a method for injecting a new migration path commit 250a5fa5ae8cb05807af022aa4168907772c15f8 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 00:56:09 2012 -0500 Remove missing constant (use string) and add gemcache cleaner commit 37ad6063fce0a41dddedb857fa49aa2c4834a508 Merge: d47ee82 4be0361 Author: Tod Beardsley <todb@metasploit.com> Date: Sun Apr 15 00:40:16 2012 -0500 Merge branch 'master-clone' into rails3-clone commit d47ee82ad7e66de53dd3d3a65649cc37299a2479 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 00:30:03 2012 -0500 cleanup leftovers from gems commit 6d883b5aa8a3a7ddbcde5bfd4521d57c5b30d3c2 Author: HD Moore <hd_moore@rapid7.com> Date: Sun Apr 15 00:25:47 2012 -0500 MDM update with purged DBSave module commit 71e4f2d81f6da221b76150562a16c730888f5925 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 23:19:37 2012 -0500 Add new mdm commit 651cd5adac8211d65e0c8079371d8264e549533a Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 23:19:13 2012 -0500 Update mdm commit 0191a8bd0acec30ddb2a9e9c291111a12378537f Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 22:30:40 2012 -0500 This fixes numerous cases of missed Mdm:: prefixes on db objects commit a2a9bb3f2148622c135663dead80b3367b6f7695 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 18:30:18 2012 -0500 Add eventmachine commit 301ddeb12b906ed3c508613ca894347bedc3b499 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 18:18:12 2012 -0500 A nicer error for folks who need to upgrade pg commit fa6bde1e67b12e2d3d9978f59bbc98e0c1a1a707 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 17:54:55 2012 -0500 Remove bundler requirements commit 2e3ab9ed211303f1116e602b9a450141b71e56a4 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 17:35:38 2012 -0500 Pull in eventmachine with actual .so's this time commit 901fb33ff6b754ce2c2cfd51e3b0b669f6ec600b Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 17:19:12 2012 -0500 Update deps, still need to add eventmachine commit 6b0e17068e8caa0601f3ef81e8dbdb672758fcbe Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 13:07:06 2012 -0500 Handle older installer environments and only allow binary gems when the environment specifically asks for it commit b98eb7873a6342834840424699caa414a5cb172a Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 04:05:13 2012 -0500 Bump version to -testing commit 6ac508c4ba3fdc278aaf8cfe2c58d01de3395431 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 02:25:09 2012 -0500 Remove msf3 subdir commit a27dac5067635a95b4cbb773df1985f2a2dc2c5a Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 02:24:39 2012 -0500 Remove the old busted external commit 5fb5a0fc642b6c301934c319db854cc3145427a1 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 02:03:10 2012 -0500 Add the gemcache loader commit 09e2d89dfd09b9ac0c123fcc4e19816c86725627 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Apr 14 02:02:23 2012 -0500 Purge gemfile/bundler configure in exchange for new gemcache setup commit 3cc0264e1cfb027b515d7f24b95a74b023bd905c Author: Tod Beardsley <todb@metasploit.com> Date: Thu Apr 12 14:11:45 2012 -0500 Mode change on modicon_ladder.apx commit c18b3d56efd639e461137acdc76b4b283fe978d4 Author: HD Moore <hd_moore@rapid7.com> Date: Thu Apr 12 01:38:56 2012 -0500 The go faster button commit ca2a67d51d6d4c7c3ca2e745f8b018279aef668a Merge: 674ee09 b8129f9 Author: Tod Beardsley <todb@metasploit.com> Date: Mon Apr 9 15:50:33 2012 -0500 Merge branch 'master-clone' into rails3-clone Picking up Packetfu upstream changes, all pretty minor commit 674ee097ab8a6bc9608bf377479ccd0b87e7302b Merge: e9513e5 a26e844 Author: Tod Beardsley <todb@metasploit.com> Date: Mon Apr 9 13:57:26 2012 -0500 Merge branch 'master-clone' into rails3-clone Conflicts: lib/msf/core/handler/reverse_http.rb lib/msf/core/handler/reverse_https.rb modules/auxiliary/scanner/discovery/udp_probe.rb modules/auxiliary/scanner/discovery/udp_sweep.rb Resolved conflicts with the reverse_http handlers and the udp probe / scanners byt favoring the more recent changes (which happened to be the intent anyway). The reverse_http and reverse_https changes were mine so I know what the intent was, and @dmaloney-r7 changed udp_probe and udp_sweep to use pcAnywhere_stat instead of merely pcAnywhere, so the intent is clear there as well. commit e9513e54f984fdb100c13b44a1724246779ccb76 Author: David Maloney <dmaloney@melodie.gateway.2wire.net> Date: Fri Apr 6 18:21:46 2012 -0500 Some fixes to how services get reported to prevent issues with the web interface commit adeb44e9aaf1a329a0e587d2b26e678398730422 Author: David Maloney <David_Maloney@rapid7.com> Date: Mon Apr 2 15:39:46 2012 -0500 Some corrections to pcAnywhere discovery modules to distinguish between the two services commit b13900176484fea8f5217a2ef925ae2ad9b7af47 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Mar 31 12:03:21 2012 -0500 Enable additional migration-path parameters, use a temporary directory to bring the database online commit 526b4c56883f461417f71269404faef38639917c Author: David Maloney <David_Maloney@rapid7.com> Date: Wed Mar 28 23:24:56 2012 -0500 A bunch of Mdsm fixes for .kind_of? calls, to make sure we ponit to the right place commit 2cf3143370af808637d164ce59400605300f922c Author: HD Moore <hd_moore@rapid7.com> Date: Mon Mar 26 16:22:09 2012 -0500 Check for ruby 2.0 as well as 1.9 for encoding override commit 4d0f51b76d89f00f7acbce6b1f00dc6e4c4545ee Author: HD Moore <hd_moore@rapid7.com> Date: Mon Mar 26 15:36:04 2012 -0500 Remove debug statement commit f5d2335e7745aa1a354f4d6c8fc9d0b3876c472a Author: HD Moore <hd_moore@rapid7.com> Date: Mon Mar 26 15:01:55 2012 -0500 Be explicit about the Mdm namespace commit bc8be225606d6ea38dd2a85ab4310c1c181a94ee Author: hdm <hdm@hypo.(none)> Date: Mon Mar 26 11:49:51 2012 -0500 Precalculate some uri strings in case the 1000-round generation fails commit 4254f419723349ffb93e4aebdaeabbd7d66bf8c0 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Sat Mar 24 14:03:44 2012 -0500 Removed some non-namespaced calls to Host commit c8190e1bb8ad365fb0d7a1c4a9173e6c739be85c Author: HD Moore <hd_moore@rapid7.com> Date: Tue Mar 20 00:37:00 2012 -0500 Purge the rvmrc, this is causing major headaches commit 76df18588917b7150a3bedf2569710a80bab51f8 Author: HD Moore <hd_moore@rapid7.com> Date: Tue Mar 20 00:31:52 2012 -0500 Switch .rvmrc to the shipping 1.9.3 version commit 7124971d0032b268f4ddf89aca125f15e284f345 Author: David Maloney <David_Maloney@rapid7.com> Date: Mon Mar 12 16:56:40 2012 -0500 Adds mixin for looking up Mime Types by extension commit b7ca8353164c43db6bacb2f3f16afa1269f66e43 Merge: a0b0c75 6b9a219 Author: Matt Buck <techpeace@gmail.com> Date: Tue Mar 6 19:38:53 2012 -0600 Merge from develop. commit a0b0c7528d2b8fabb76b2246a15004bc89239cf0 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Tue Mar 6 11:08:59 2012 -0600 Somehow migration file is new? commit 84d2b3cb1ad6290413c3ea3222ddf9932270b105 Author: David Maloney <David_Maloney@rapid7.com> Date: Wed Feb 29 16:38:55 2012 -0600 Added ability to specify headers to redirects in http server commit e50d27cda83872c616722adb03dc1a6a5e685405 Author: HD Moore <hd_moore@rapid7.com> Date: Sat Feb 4 04:44:50 2012 -0600 Tweak the event dispatcher to enable customer events without a category and trigger http request events from the main exploit mixin. Experimental commit 0e4fd2040df49df2e6cb0e8d2c6240a03d108033 Author: Matt Buck <Matthew_Buck@rapid7.com> Date: Thu Feb 2 22:09:05 2012 -0600 Change Msm -> Mdm in migrations. This is what was preventing migrations from finishing on first boot. commit c94a2961d04eee84adfd42bb01ed7a3e3846b83a Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Wed Feb 1 12:48:48 2012 -0600 Changed Gemfile to use new gem name commit 245c2063f06b4fddbfc607d243796669ef236136 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Wed Feb 1 12:47:42 2012 -0600 Did find/replace for final namespace of Mdm commit 6ed9bf8430b555dcbe62daeddb2f33bd400ab5bc Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Tue Jan 24 10:47:44 2012 -0600 Fix a bunch of namespace issues commit 2fe08d9e4226c27e78d07a00178c58f528cbc72e Author: Matt Buck <Matthew_Buck@rapid7.com> Date: Fri Jan 20 14:37:37 2012 -0600 Update Msm contstants in migrations for initial DB builds. commit 4cc6b8fb0440c6258bf70de77a9153468fea4ea5 Author: Matt Buck <Matthew_Buck@rapid7.com> Date: Fri Jan 20 14:37:25 2012 -0600 Update Gemfile.lock. commit 1cc655b678f0a054a9a783da119237fe3f67faa4 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Thu Jan 19 11:48:29 2012 -0600 Errant Workspaces needed namespace commit 607a78285582c530a68985add33ccf4d899c467a Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Tue Jan 17 15:44:02 2012 -0600 Refactored all models to use the new namespace * Every model using DBManager::* namespace is now Msm namespace * Almost all of this in msf/base/core * Some in modules commit a690cd959b3560fa2284975ca7ecca10c228fb05 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Tue Jan 17 13:41:44 2012 -0600 Move bundler setup commit dae115cc8f7619ca7a827123079cb67fb4d9354b Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Mon Jan 9 15:51:07 2012 -0600 Moved ActiveSupport dep to gem commit d32f8edb6e7f82079b775ffbc2b9a405d1f32b3b Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Mon Jan 9 14:40:05 2012 -0600 Removed model require file commit d0c74cff8c44771e566ec63b03eda10d03b25c42 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Tue Jan 3 16:06:10 2012 -0600 Update some more finds commit 4eb79ea6b58b74c309ab1f1bb0bd35fe9041de46 Author: Trevor Rosen <Trevor_Rosen@rapid7.com> Date: Tue Jan 3 14:21:15 2012 -0600 Yet another dumb commit commit a75febcb593d52fdfe930306b4275829759d81d1 Author: Trevor Rosen <trevor@catapult-creative.com> Date: Thu Dec 29 19:20:51 2011 -0600 Fixing deletion commit dc139ff2fdfc4e7cdee3901dfb863e70913d6b92 Author: Trevor Rosen <trevor@catapult-creative.com> Date: Wed Dec 7 17:06:45 2011 -0600 Fixed erroneous commit commit 531c1e611cf4d23aeb9c48350dabf7630d662d25 Author: Trevor Rosen <trevor@catapult-creative.com> Date: Mon Nov 21 16:11:35 2011 -0600 Remove AR patch stuff; attempting to debug non-connection between MSF and Pro commit 458611224189c7aa27e500aabd373d85dc2dc5c0 Author: Trevor Rosen <trevor@catapult-creative.com> Date: Fri Nov 18 16:17:27 2011 -0600 Drop ActiveRecord/ActiveSupport in preparation for upgrade
2012-04-16 04:35:38 +00:00
# state_machine [![Build Status](https://secure.travis-ci.org/pluginaweek/state_machine.png "Build Status")](http://travis-ci.org/pluginaweek/state_machine) [![Dependency Status](https://gemnasium.com/pluginaweek/state_machine.png "Dependency Status")](https://gemnasium.com/pluginaweek/state_machine)
*state_machine* adds support for creating state machines for attributes on any
Ruby class.
## Resources
API
* http://rdoc.info/github/pluginaweek/state_machine/master/frames
Bugs
* http://github.com/pluginaweek/state_machine/issues
Development
* http://github.com/pluginaweek/state_machine
Testing
* http://travis-ci.org/pluginaweek/state_machine
Source
* git://github.com/pluginaweek/state_machine.git
Mailing List
* http://groups.google.com/group/pluginaweek-talk
## 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 :)
Some brief, high-level features include:
* Defining state machines on any Ruby class
* Multiple state machines on a single class
* Namespaced state machines
* before/after/around/failure transition hooks with explicit transition requirements
* Integration with ActiveModel, ActiveRecord, DataMapper, Mongoid, MongoMapper, and Sequel
* State predicates
* State-driven instance / class behavior
* State values of any data type
* Dynamically-generated state values
* Event parallelization
* Attribute-based event transitions
* Path analysis
* Inheritance
* Internationalization
* GraphViz visualization creator
* YARD integration (Ruby 1.9+ only)
* Flexible machine syntax
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:
```ruby
class Vehicle
attr_accessor :seatbelt_on, :time_used, :auto_shop_busy
state_machine :state, :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition :on => :crash, :do => :tow
after_transition :on => :repair, :do => :fix
after_transition any => :parked do |vehicle, transition|
vehicle.seatbelt_on = false
end
after_failure :on => :ignite, :do => :log_start_failure
around_transition do |vehicle, transition, block|
start = Time.now
block.call
vehicle.time_used += Time.now - start
end
event :park do
transition [:idling, :first_gear] => :parked
end
event :ignite do
transition :stalled => same, :parked => :idling
end
event :idle do
transition :first_gear => :idling
end
event :shift_up do
transition :idling => :first_gear, :first_gear => :second_gear, :second_gear => :third_gear
end
event :shift_down do
transition :third_gear => :second_gear, :second_gear => :first_gear
end
event :crash do
transition all - [:parked, :stalled] => :stalled, :if => lambda {|vehicle| !vehicle.passed_inspection?}
end
event :repair do
# The first transition that matches the state and passes its conditions
# will be used
transition :stalled => :parked, :unless => :auto_shop_busy
transition :stalled => same
end
state :parked do
def speed
0
end
end
state :idling, :first_gear do
def speed
10
end
end
state all - [:parked, :stalled, :idling] do
def moving?
true
end
end
state :parked, :stalled, :idling do
def moving?
false
end
end
end
state_machine :alarm_state, :initial => :active, :namespace => 'alarm' do
event :enable do
transition all => :active
end
event :disable do
transition all => :off
end
state :active, :value => 1
state :off, :value => 0
end
def initialize
@seatbelt_on = false
@time_used = 0
@auto_shop_busy = true
super() # NOTE: This *must* be called, otherwise states won't get initialized
end
def put_on_seatbelt
@seatbelt_on = true
end
def passed_inspection?
false
end
def tow
# tow the vehicle
end
def fix
# get the vehicle fixed by a mechanic
end
def log_start_failure
# log a failed attempt to start the vehicle
end
end
```
**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:
```ruby
vehicle = Vehicle.new # => #<Vehicle:0xb7cf4eac @state="parked", @seatbelt_on=false>
vehicle.state # => "parked"
vehicle.state_name # => :parked
vehicle.human_state_name # => "parked"
vehicle.parked? # => true
vehicle.can_ignite? # => true
vehicle.ignite_transition # => #<StateMachine::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>
vehicle.state_events # => [:ignite]
vehicle.state_transitions # => [#<StateMachine::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>]
vehicle.speed # => 0
vehicle.moving? # => false
vehicle.ignite # => true
vehicle.parked? # => false
vehicle.idling? # => true
vehicle.speed # => 10
vehicle # => #<Vehicle:0xb7cf4eac @state="idling", @seatbelt_on=true>
vehicle.shift_up # => true
vehicle.speed # => 10
vehicle.moving? # => true
vehicle # => #<Vehicle:0xb7cf4eac @state="first_gear", @seatbelt_on=true>
# A generic event helper is available to fire without going through the event's instance method
vehicle.fire_state_event(:shift_up) # => true
# Call state-driven behavior that's undefined for the state raises a NoMethodError
vehicle.speed # => NoMethodError: super: no superclass method `speed' for #<Vehicle:0xb7cf4eac>
vehicle # => #<Vehicle:0xb7cf4eac @state="second_gear", @seatbelt_on=true>
# The bang (!) operator can raise exceptions if the event fails
vehicle.park! # => StateMachine::InvalidTransition: Cannot transition state via :park from :second_gear
# Generic state predicates can raise exceptions if the value does not exist
vehicle.state?(:parked) # => false
vehicle.state?(:invalid) # => IndexError: :invalid is an invalid name
# Namespaced machines have uniquely-generated methods
vehicle.alarm_state # => 1
vehicle.alarm_state_name # => :active
vehicle.can_disable_alarm? # => true
vehicle.disable_alarm # => true
vehicle.alarm_state # => 0
vehicle.alarm_state_name # => :off
vehicle.can_enable_alarm? # => true
vehicle.alarm_off? # => true
vehicle.alarm_active? # => false
# Events can be fired in parallel
vehicle.fire_events(:shift_down, :enable_alarm) # => true
vehicle.state_name # => :first_gear
vehicle.alarm_state_name # => :active
vehicle.fire_events!(:ignite, :enable_alarm) # => StateMachine::InvalidTransition: Cannot run events in parallel: ignite, enable_alarm
# Human-friendly names can be accessed for states/events
Vehicle.human_state_name(:first_gear) # => "first gear"
Vehicle.human_alarm_state_name(:active) # => "active"
Vehicle.human_state_event_name(:shift_down) # => "shift down"
Vehicle.human_alarm_state_event_name(:enable) # => "enable"
# States / events can also be references by the string version of their name
Vehicle.human_state_name('first_gear') # => "first gear"
Vehicle.human_state_event_name('shift_down') # => "shift down"
# Available transition paths can be analyzed for an object
vehicle.state_paths # => [[#<StateMachine::Transition ...], [#<StateMachine::Transition ...], ...]
vehicle.state_paths.to_states # => [:parked, :idling, :first_gear, :stalled, :second_gear, :third_gear]
vehicle.state_paths.events # => [:park, :ignite, :shift_up, :idle, :crash, :repair, :shift_down]
# Find all paths that start and end on certain states
vehicle.state_paths(:from => :parked, :to => :first_gear) # => [[
# #<StateMachine::Transition attribute=:state event=:ignite from="parked" ...>,
# #<StateMachine::Transition attribute=:state event=:shift_up from="idling" ...>
# ]]
# Skipping state_machine and writing to attributes directly
vehicle.state = "parked"
vehicle.state # => "parked"
vehicle.state_name # => :parked
# *Note* that the following is not supported (see StateMachine::MacroMethods#state_machine):
# vehicle.state = :parked
```
## 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,
```ruby
class Vehicle
include ActiveModel::Dirty
include ActiveModel::Validations
include ActiveModel::Observing
attr_accessor :state
define_attribute_methods [:state]
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition any => :parked do |vehicle, transition|
vehicle.seatbelt = 'off'
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 < ActiveModel::Observer
# Callback for :ignite event *before* the transition is performed
def before_ignite(vehicle, transition)
# log message
end
# Generic transition callback *after* the transition is performed
def after_transition(vehicle, transition)
Audit.log(vehicle, transition)
end
# Generic callback after the transition fails to perform
def after_failure_to_transition(vehicle, transition)
Audit.error(vehicle, transition)
end
end
```
For more information about the various behaviors added for ActiveModel state
machines and how to build new integrations that use ActiveModel, see
`StateMachine::Integrations::ActiveModel`.
### ActiveRecord
The ActiveRecord integration adds support for database transactions, automatically
saving the record, named scopes, validation errors, and observers. For example,
```ruby
class Vehicle < ActiveRecord::Base
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition any => :parked do |vehicle, transition|
vehicle.seatbelt = 'off'
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 < ActiveRecord::Observer
# Callback for :ignite event *before* the transition is performed
def before_ignite(vehicle, transition)
# log message
end
# Generic transition callback *after* the transition is performed
def after_transition(vehicle, transition)
Audit.log(vehicle, transition)
end
end
```
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,
```ruby
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,
```ruby
class Vehicle
include Mongoid::Document
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition any => :parked do |vehicle, transition|
vehicle.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 < Mongoid::Observer
# Callback for :ignite event *before* the transition is performed
def before_ignite(vehicle, transition)
# log message
end
# Generic transition callback *after* the transition is performed
def after_transition(vehicle, transition)
Audit.log(vehicle, transition)
end
end
```
For more information about the various behaviors added for Mongoid state
machines, see `StateMachine::Integrations::Mongoid`.
### MongoMapper
The MongoMapper integration adds support for automatically saving the record,
basic scopes, validation errors and callbacks. For example,
```ruby
class Vehicle
include MongoMapper::Document
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
after_transition any => :parked do |vehicle, transition|
vehicle.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
```
For more information about the various behaviors added for MongoMapper state
machines, see `StateMachine::Integrations::MongoMapper`.
### Sequel
Like the ActiveRecord integration, the Sequel integration adds support for
database transactions, automatically saving the record, named scopes, validation
errors and callbacks. For example,
```ruby
class Vehicle < Sequel::Model
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
```
For more information about the various behaviors added for Sequel state
machines, see `StateMachine::Integrations::Sequel`.
## Additional Topics
### Symbols vs. Strings
In all of the examples used throughout the documentation, you'll notice that
states and events are almost always referenced as symbols. This isn't a
requirement, but rather a suggested best practice.
You can very well define your state machine with Strings like so:
```ruby
class Vehicle
state_machine :initial => 'parked' do
event 'ignite' do
transition 'parked' => 'idling'
end
# ...
end
end
```
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:
```ruby
class Vehicle
state_machine do
event :ignite do
transition :parked => 'idling'
end
end
end
# => 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:
```ruby
class Vehicle
state_machine :initial => :parked do
event :ignite do
transition :parked => :idling
end
end
end
v = Vehicle.new # => #<Vehicle:0xb71da5f8 @state="parked">
v.state?('parked') # => true
v.state?(:parked) # => true
```
### 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:
```ruby
class Vehicle
state_machine :initial => :parked do
before_transition :from => :parked, :except_to => :parked, :do => :put_on_seatbelt
after_transition :to => :parked do |transition|
self.seatbelt = 'off' # self is the record
end
event :ignite do
transition :from => :parked, :to => :idling
end
end
end
```
#### 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:
```ruby
class Vehicle
state_machine :initial => :parked do
...
state :parked do
transition :to => :idling, :on => [:ignite, :shift_up], :if => :seatbelt_on?
def speed
0
end
end
state :first_gear do
transition :to => :second_gear, :on => :shift_up
def speed
10
end
end
state :idling, :first_gear do
transition :to => :parked, :on => :park
end
end
end
```
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:
```ruby
class Vehicle
state_machine :initial => :parked do
...
transition :parked => :idling, :on => [:ignite, :shift_up]
transition :first_gear => :second_gear, :second_gear => :third_gear, :on => :shift_up
transition [:idling, :first_gear] => :parked, :on => :park
transition [:idling, :first_gear] => :parked, :on => :park
transition all - [:parked, :stalled] => :stalled, :unless => :auto_shop_busy?
end
end
```
Notice that in these alternative syntaxes:
* You can continue to configure `:if` and `:unless` conditions
* 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:
```ruby
class Vehicle
state_machine :state, :initial => :parked do
event :park do
transition [:idling, :first_gear] => :parked
end
...
end
end
```
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:
```ruby
class Vehicle
attr_accessor :state
# Replace this with an external source (like a db)
def transitions
[
{:parked => :idling, :on => :ignite},
{:idling => :first_gear, :first_gear => :second_gear, :on => :shift_up}
# ...
]
end
# Create a state machine for this vehicle instance dynamically based on the
# transitions defined from the source above
def machine
vehicle = self
@machine ||= Machine.new(vehicle, :initial => :parked) do
vehicle.transitions.each {|attrs| transition(attrs)}
# Persist the state on the vehicle itself
after_transition do
vehicle.state = vehicle.machine.state
vehicle.save
end
end
end
def save
# Save the state change...
end
end
# Generic class for building machines
class Machine
def self.new(object, *args, &block)
machine = Class.new do
def definition
self.class.state_machine
end
end
machine.state_machine(*args, &block)
machine.new
end
end
vehicle = Vehicle.new # => #<Vehicle:0xb7236b50>
vehicle.machine # => #<#<Class:0xb723541c>:0xb722fa30 @state="parked">
vehicle.machine.state # => "parked"
vehicle.machine.ignite # => true
vehicle.machine.state # => "idling
vehicle.state # => "idling"
vehicle.machine.state_transitions # => [#<StateMachine::Transition ...>]
vehicle.machine.definition.states.keys # => :first_gear, :second_gear, :parked, :idling
```
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:
```ruby
require 'state_machine/core'
class Vehicle
extend StateMachine::MacroMethods
state_machine do
# ...
end
end
```
If you're using a gem loader like Bundler, you can explicitly indicate which
file to load:
```ruby
# In Gemfile
...
gem 'state_machine', :require => 'state_machine/core'
```
## 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](http://www.graphviz.org]).
This requires that both the `ruby-graphviz` gem and graphviz library be
installed on the system.
#### Examples
To generate a graph for a specific file / class:
```bash
rake state_machine:draw FILE=vehicle.rb CLASS=Vehicle
```
To save files to a specific path:
```bash
rake state_machine:draw FILE=vehicle.rb CLASS=Vehicle TARGET=files
```
To customize the image format / orientation:
```bash
rake state_machine:draw FILE=vehicle.rb CLASS=Vehicle FORMAT=jpg ORIENTATION=landscape
```
To generate multiple state machine graphs:
```bash
rake state_machine:draw FILE=vehicle.rb,car.rb CLASS=Vehicle,Car
```
To use human state / event names:
```bash
rake state_machine:draw FILE=vehicle.rb CLASS=Vehicle HUMAN_NAMES=true
```
**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](http://www.cs.usfca.edu/~jbovet/vas.html)
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:
```yaml
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.
#### 1. Install the gem
If using Rails 2.x:
```ruby
# In config/environment.rb
...
Rails::Initializer.run do |config|
...
config.gem 'state_machine', :version => '~> 1.0'
...
end
```
If using Rails 3.x or up:
```ruby
# In Gemfile
...
gem 'state_machine'
gem 'ruby-graphviz', :require => 'graphviz' # Optional: only required for graphing
```
As usual, run `bundle install` to load the gems.
#### 2. Create a model
Create a model with a field to store the state, along with other any other
fields your application requires:
```bash
$ rails generate model Vehicle state:string
$ rake db:migrate
```
#### 3. Configure the state machine
Add the state machine to your model. Following the examples above,
*app/models/vehicle.rb* might become:
```ruby
class Vehicle < ActiveRecord::Base
state_machine :initial => :parked do
before_transition :parked => any - :parked, :do => :put_on_seatbelt
...
end
end
```
#### 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,
```bash
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:
```ruby
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.
For example,
```bash
rake state_machine:draw CLASS=Vehicle
```
## Testing
To run the core test suite (does **not** test any of the integrations):
```bash
bundle install
bundle exec rake test
```
To run integration tests:
```bash
bundle install
rake appraisal:install
rake appraisal:test
```
You can also test a specific version:
```bash
rake appraisal:active_model-3.0.0 test
rake appraisal:active_record-2.0.0 test
rake appraisal:data_mapper-0.9.4 test
rake appraisal:mongoid-2.0.0 test
rake appraisal:mongo_mapper-0.5.5 test
rake appraisal:sequel-2.8.0 test
```
## Caveats
The following caveats should be noted when using state_machine:
* Overridden event methods won't get invoked when using attribute-based event transitions
* **DataMapper**: Attribute-based event transitions are disabled when using dm-validations 0.9.4 - 0.9.6
* **JRuby**: around_transition callbacks in ORM integrations won't work on JRuby since it doesn't support continuations
* **Factory Girl**: Dynamic initial states don't work because of the way factory_girl
builds objects. You can work around this in a few ways:
1. Use a default state that is common across all objects and rely on events to
determine the actual initial state for your object.
2. Assuming you're not using state-driven behavior on initialization, you can
re-initialize states after the fact:
```ruby
# Re-initialize in FactoryGirl
FactoryGirl.define do
factory :vehicle do
after_build {|user| user.send(:initialize_state_machines, :dynamic => :force)}
end
end
# Alternatively re-initialize in your model
class Vehicle < ActiveRecord::Base
...
before_validation :on => :create {|user| user.send(:initialize_state_machines, :dynamic => :force)}
end
```
## Dependencies
* Ruby 1.8.6 or later
If using specific integrations:
* [ActiveModel](http://rubyonrails.org) integration: 3.0.0 or later
* [ActiveRecord](http://rubyonrails.org) integration: 2.0.0 or later
* [DataMapper](http://datamapper.org) integration: 0.9.4 or later
* [Mongoid](http://mongoid.org) integration: 2.0.0 or later
* [MongoMapper](http://mongomapper.com) integration: 0.5.5 or later
* [Sequel](http://sequel.rubyforge.org) integration: 2.8.0 or later
If graphing state machine:
* [ruby-graphviz](http://github.com/glejeune/Ruby-Graphviz): 0.9.0 or later