state_machine: Test whether an object can take a transition

Updated . Posted . Visible to the public.

When using state_machine Show archive.org snapshot you sometimes need to know whether an object may execute a certain transition. Let's take an arbitrary object such as a blog article as an example that has those states:

A -> B -> C -> D

Additionally, you have transitions between the states as shown above. Let's call the transition between 'A' and 'B' transition_ab for simplicity. \
Given an object in state 'A'. You can call object.transition_ab but calling object.transition_bc! will obviously fail because there's no such transition for state 'A'.

Now if you need to check whether you can call transition_ab or not, you can use object.can_transition_ab? which checks if an appropriate transition exists. \
This is often useful in views where might think about writing [state_A, state_B].include? object.state (which you should not).

Keep in mind that this will not call any validations or other filters on your object. The transition might still fail.

Thomas Eisenbarth
Last edit
Keywords
state, machine, change, might, can, possible
License
Source code in this card is licensed under the MIT License.
Posted by Thomas Eisenbarth to makandra dev (2011-11-08 20:23)