Visualizing state_machine in Rails

Often, an app’s models need a lifecycle, transitioning between different states according to different business rules. The leading contender for abstracting this is the state_machine gem for Rails. (There are other options too, but not as rich.) It allows you to create a finite state machine on top of ActiveRecord, including all the goodness of events, constrained transitions, and many others.

As much as I believe the code should be legible enough for easy reading, sometimes a picture is a worth a thousand words. This gem comes with GraphViz integration, enabling to you create visual representations of your state machines. (GraphViz is a tool for turning textual descriptions of directed or undirected graphs into pictures) This feature is almost a footnote on the gem documentation, but it’s the killer feature for any skeptics that might be tempted to roll their lifecycle management code (usually by a simple “state” string in the model).

The picture to the right is generated with the following command:

rake state_machine:draw CLASS=Vehicle

That’s all pretty nifty, but what if you need an even fancier picture? OmniGraffle to the rescue! The mac’s über diagraming tool can import graphviz files directly, so it’s just a matter of calling the rake task with the right FORMAT, and opening it:

 

rake state_machine:draw FORMAT=dot
open -a /Applications/OmniGraffle\ 5.app Vehicle_state.dot

And now you can make graphic changes to your heart’s content. My tinkering for a few results in the image to the left.

Leave a Reply