-
Notifications
You must be signed in to change notification settings - Fork 1
Sequential Transitions
CodeMeister edited this page Feb 28, 2023
·
1 revision
Sequential transitions, where each state can transition to the previous and/or
next state is a common implementation within both form and service objects.
The make_sequential
option is included to simplify the configuration.
In this example, both attributes
:status
andstatus_test
have the same transitions.
class Post < ActiveRecord::Base
include StateGate
state_gate :status do
state :draft, transitions_to: :pending
state :pending, transitions_to: [:draft, :published]
state :published, transitions_to: [:pending, :archived]
state :archived, transitions_to: :published
end
state_gate :status_test do
state :draft
state :pending
state :published
state :archived
make_sequential
end
end
Post.status_transitions #=> { draft: [:pending],
#=> pending: [:draft, :published],
#=> published: [:pending, :archived],
#=> archived: [:published] }
Post.status_Test_transitions #=> { draft: [:pending],
#=> pending: [:draft, :published],
#=> published: [:pending, :archived],
#=> archived: [:published] }
The
:one_way
parameter will restrict transition to 'next state' only.
class Post < ActiveRecord::Base
include StateGate
state_gate :status do
state :draft, transitions_to: :pending
state :pending, transitions_to: [:draft, :published]
state :published, transitions_to: [:pending, :archived]
state :archived, transitions_to: :published
make_sequential :one_way
end
end
Post.status_transitions #=> { draft: [:pending],
#=> pending: [:published],
#=> published: [:archived],
#=> archived: [] }
The
:loop
parameter will allow the first and last states to transition to each other, taking into account the:one_way
option.
class Post < ActiveRecord::Base
include StateGate
state_gate :status do
state :draft
state :pending
state :published
state :archived
make_sequential :loop
end
state_gate :status_test do
state :draft
state :pending
state :published
state :archived
make_sequential :one_way, :loop
end
end
Post.status_transitions #=> { draft: [:archived, :pending],
#=> pending: [:draft, :published],
#=> published: [:pending, :archived],
#=> archived: [:published, :draft] }
Post.status_Test_transitions #=> { draft: [:pending],
#=> pending: [:published],
#=> published: [:archived],
#=> archived: [:draft] }