-
Notifications
You must be signed in to change notification settings - Fork 1
Namespace with Prefix & Suffix
CodeMeister edited this page Feb 28, 2023
·
1 revision
When two attributes within the same model each have a state with the same name, there will be conflicts when creating scope and predicate methods.
In this example the class scope
#draft
and the instance predicate.draft?
will be created as normal for the:status
state_gate, but will raise an exception when creating the:invoice_status
state_gate.
class Post < ActiveRecord::Base
include StateGate
state_gate :status do
state :draft
state :pending
state :published
state :archived
end
state_gate :invoice_status do
state :draft
state :finalised
state :paid
end
end
<StateGate::ConflictError>
Theprefix
and postfix
options provide a mechanism to namespace states, avoiding
this issue.
The
prefix
option prepends each state with the given name, while thesuffix
option appends it to the end of each state.
class Post < ActiveRecord::Base
include StateGate
state_gate :status do
state :draft
state :pending
state :published
state :archived
end
state_gate :job_status do
state :queued
state :processing
state :completed
prefix :job
end
state_gate :invoice_status do
state :draft
state :issued
state :paid
suffix :invoice
end
end
Post.draft #=> <ArctiveRecord::Relation>
Post.pending #=> <ArctiveRecord::Relation>
Post.published #=> <ArctiveRecord::Relation>
Post.archived #=> <ArctiveRecord::Relation>
Post.job_queued #=> <ArctiveRecord::Relation>
Post.job_processing #=> <ArctiveRecord::Relation>
Post.job_archived #=> <ArctiveRecord::Relation>
Post.draft_invoice #=> <ActiveRecord::Relation>
Post.issued_invoice #=> <ActiveRecord::Relation>
Post.paid_invoice #=> <ActiveRecord::Relation>