Todd Todd - 3 months ago 9
Ruby Question

How to get a list of states which come before a given state with Ruby `state_machine` gem?

Considering the state_machine gem, how does one select a set of state names/symbols that come before a given state?

Lets say I have four states:

:pending
,
:signature_needed
,
:ordered
,
:finalized
. Assume a linear progression from the initial (
:pending
) to the final (
:finalized
) state.

How would I get all states which come before
:ordered
? I would expect a result like
[:pending, :signature_needed]
.

Note: I just realized, after trying to figure out why this functionality is not provided, that
state_machine
is not currently supported (as I was going to make a PR that added this feature).

Answer

There is no such functionality built into the (currently unmaintained) state_machine gem. Since its entirely possible for non linear state transitions, it may be extremely complex, and quite unpredictable, to accurately describe "which state comes before another state." Thus, each application which makes use of the state_machine gem will need to create its own mixin to dynamically determine which states in the cycle come before and after each other.

Credit for answer goes to the comments below the OP.