State Machine as a Service with aasm gem | NetEngine

State Machine as a Service with aasm gem

When handling state changes or object and logic condition changes, one of the most useful gems is aasm. However, after many years I find that it’s often under-utilised and even mis-used.

It’s really easy to grab the aasm gem and begin implementing the ActiveRecord methodology. This implementation is effective if the state and it’s dependencies are only models and providing you are not creating circular dependencies.

To get your head in the game here’s a quick example we came across that required us to implement something new:

Of course, we might have more transitions between those cases, but for this scenario, four will suffice.

If we go with the normal Active Record style, our code might look something like this:

Even when the previous approach is quick and simpler. There are a few cons:

A simpler approach would be using the state machine as a service, like this:

To achieve this implementation we only need to be aware of 2 sections. Everything else is your own code:

And we need to make our changes persistent:

Considering this approach we will get two huge benefits: