Skip to content

Instance Methods for Transitions

CodeMeister edited this page Feb 28, 2023 · 1 revision

instance methods:

  • .attr_transitions
    • Returns an Array of the states the attribute may transition to, based on its current value.
  • .attr_transitions_to?
    • Returns true if the attribute may transition from its current value to a given 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_transitions       #=> [:pending]
post.status = :pending        #=> 'pending'
post.status_transitions       #=> [:draft, :published]
post.status = :force_archived #=> 'archived'
post.status_transitions       #=> []

post.status = :force_draft              #=> 'draft'
post.status_transitions_to?(:pending)   #=> true
post.status_transitions_to?('pending')  #=> true
post.status_transitions_to?(:publised)  #=> false