Lately I have been using the wonderful
acts_as_state_machine plugin for lots of cool stuff in my rails applications. The problem that I have run into though, is visualizing the state transitions that I have created. Typically, when I first learned about state machines back in Electrical Engineering days, we drew cool diagrams with bubbles to represent the states and arrows to show the state transitions (a.k.a state transition diagrams). I have found these to be very helpful. But I wanted to a way to automatically create these.
My first problem was, how do I dynamically create graphs? This was solved when I found out about this: Graphviz, an open source graph visualization language that many software packages understand. There are stand-alone graph readers available as well as tools like OmniGraffle for the mac which can read this format. We will create our diagrams in this format (.dot).
My solution was inspired by Dave Thomas and his annotate_models plugin. I created a plugin that is triggered as a rake task, i.e.
rake annotate_states I used Dave’s code to guide me on how to step through all the model classes, then I added additional logic to filter out all model classes that didnt use actsasstate_machine. I then introspected on the remaining list and got a list of states and transitions so that I could build the diagram.
You can install the plugin in the usual way, navigate to the root of your application and type
script/plugin install http://svn.silverchairsolutions.com/annotate_states.
After installing the plugin (and checking that it lists as a rake task by typing rake -T) you can create the .dot files for your application by typing
rake annotate_states. Each model file in your application that uses
acts_as_state_machine should produce a state transition diagram in the root of your application.
Hope you enjoy it!