RubyFlow The Ruby and Rails community linklog

state_machine Officially Announced

state_machine, an FSM library for Ruby, has been officially announced. Features include ActiveRecord / DataMapper / Sequel integration, flexible before/after transition hooks, state-driven behavior, GraphViz visualizations, and more.

Comments

I’ve started to use this, and it is working well! Thanks for posting.

This looks pretty comprehensive. Would you mind indicating, if you know, the advantages/differences from the rubyist-AASM gem, which has been the goto State Machine plugin thus far?

Having used both (although AASM far more extensively) I can comment a bit on that…

State_machine (SM?) integrates more naturally with datamapper and sequel. It’s possible with AASM, but you need to write your own state persistence methods, and I’ve found that, even doing this, there are some things that don’t behave quite right. Basically, if you’re not using ActiveRecord, SM is definitely the optimal choice.

Also, it is impossible (AFAIK) to have multiple state machines on a single model with AASM. This isn’t a very common use case of course, but just last week I greatly simplified a very complex export process by adding a second state machine to a model.

I also prefer SM’s DSL over AASM’s, which especially shines when you have one transition that changes from multiple states to multiple states. Saves a lot on typing, and is easier to read. The ability to transition from any current state to a specific state is also a welcome addition. You can imagine having a complex state machine with many states, but with one error state that can be reached from anywhere – this is a pain to build in AASM, but fairly simple in SM.

AASM has one thing going for it, though: It’s very simple to understand, and is composed of surprisingly little code. So if you want to hack on a state machine to meld it to your own purposes, AASM might be the way to go.

I think Brian hit the nail right on the head. Each feature listed in this post touched on something that’s not available in AASM. My favorites tend to be the flexibility of transition callbacks and the syntactic sugar. Everything else is just icing, though there’s a lot of it.

Other than what’s already listed, there’s namespaced machines (like shipment_pending?, shipment_delivered?, etc.), inheritance support, dynamically-generated state values, easier method overriding, and internationalization. I think the easiest way to see the differences is to look at some of the examples in the library.

Hope that helps!

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in