Skip to content

Forcing a State Change

CodeMeister edited this page Feb 28, 2023 · 1 revision

There are occasions when it's beneficial to be able to force the change from one state to another:

  • When unit testing transitions, it's enourmously helpful to be able to set the initial state.
  • In production, it occasionally happens that an individual record needs to be manually updated. Being able to set the state directly allows updating from the console, rather than the databse.
  • When demonstrating a new feature, scenario walkthroughs can be easily configred in real time.

:force_<state>

Prepending the state name with force_ will by-pass transition checking and directly set the new state.

example:

class Post < ActiveRecord::Base
  include StateGate

  state_gate :status do
    state :draft,     transitions_to: :pending
    state :pending,   transitions_to: [:published, :draft]
    state :published, transitions_to: :archived
    state :archived
  end
end

post = Post.new
post.status                      #=> 'draft'
post.status = :published         #=> <ArgumentError>
post.status = :force_published   #=> 'published'

Clone this wiki locally