Stateology is an implementation of the State Pattern using the Mixology C extension. Stateology follows closely the LSL State Pattern implementation and can support a similar syntax.
The following features are supported:
- Dynamic switching between states (mixing and unmixing modules)
- Optional state_entry() and state_exit() hooks for each state (automatically called upon state entry and exit)
- Support for nested states
- States are cleanly inherited by subclasses
- NO MAGIC! Stateology does not use any behind-the-scenes method aliasing nor does it make use of any hooks.
Use as in the following:
class Sample
include Stateology
state(:Happy) {
def state_entry
puts "entering Happy state"
end
def do_something
puts "Pets a puppy"
end
def state_exit
puts "exiting Happy state"
end
}
state(:Angry) {
def state_entry
puts "entering Angry state"
end
def do_something
puts "Kicks a puppy"
end
def state_exit
puts "exiting Angry state"
end
}
end
s = Sample.new
# switch to Happy state
s.state :Happy
# (automatic call to state_entry) => "entering Happy state"
s.do_something #=> "Pets a puppy"
# now switch to Angry state
s.state :Angry
# (automatic call to state_exit) => "exiting Happy state"
# (automatic call to state_entry) => "entering Angry state"
s.do_something #=> "Kicks a puppy"
# now switch back to no state
s.state nil
# (automatic call to state_exit) => "exiting Angry state"
Download and Gem
You can download Stateology here: http://github.com/banister/state-ology/tree/master
Or install the Gem: sudo gem install stateology
Filed under: programming, ruby | Tagged: mixology, ruby, ruby finite state machine, ruby FSM, ruby states, state pattern, stateology
[...] Updating A C Extension For Ruby 1.9.1 Posted on February 13, 2009 by banisterfiend One of my favourite C extensions for Ruby 1.8.6 is Mixology. Using Mixology one can dynamically mix and unmix modules from inheritance chains. Some very cool things have been done with this kind of functionality including _why’s mixico, the decorator pattern, and the state pattern. [...]