-
Notifications
You must be signed in to change notification settings - Fork 1
Creating a StateGate
CodeMeister edited this page Mar 1, 2023
·
10 revisions
-
include StateGatewithin the model class.
- create the state-gate on the
Stringattribute
- pass a block defining the individual states with their allowed transitions.
This example creates a minimal state-gate on the :status attribute of the Post class,
allowing any state to transition to any other state without restriction.
class Post < ActiveRecord::Base
include StateGate
state_gate :status do
state :draft
state :pending
state :published
state :archived
end
end
Post.new.status #=> 'draft'This example creates a basic state-gate on the :status attribute of the Post class,
defining the allowed transitions between states.
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 = :pending #=> 'pending'
post.status = :draft #=> 'draft'
post.status = :pending #=> 'pending'
post.status = :published #=> 'published'
post.status = 'archived' #=> 'archived'
post.status = :published #=> <ArgumentError>
This example creates a more complex state-gate with a prefix, a suffix, no scopes and one-way, looping, sequential transitions.
class UKTrafficLight < ActiveRecord::Base
include StateGate
state_gate :status do
state :green
state :yellow
state :red
state :red_and_yellow
default :red
prefix :traffic
suffix :light
no_scopes
make_sequential :one_way, :loop
end
end