Read more

state_machine: Test whether an object can take a transition

Thomas Eisenbarth
November 08, 2011Software engineer at makandra GmbH

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
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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.

Posted by Thomas Eisenbarth to makandra dev (2011-11-08 21:23)