Skip to content

Class Methods for States

CodeMeister edited this page Feb 28, 2023 · 1 revision

class methods:

  • #attrs
    • Returns an Array of the Symbol names for each state, in the order each state was defined.
  • #human_attrs
    • Returns an Array of the String display names for each state, in the order each state was defined.
  • #attrs_for_select
    • While it's bad practice to set a state directly from user input, it's quite common to allow the user to search, or filter, by a specific state. This method returns an Array of Arrays, each containing both the String display name and Symbol name for each state, suitable for use in a form select field.
    • By default, results are in the order the states were defined, but passing :sorted will re-order them alphabetically by human name.

example:

class Post < ActiveRecord::Base
  include StateGate

  state_gate :status do
    state :draft
    state :pending, human: 'Pending Approval'
    state :published
    state :archived
  end
end

Post.statuses                     #=> [:draft, :pending, :published, :archived]

Post.human_statuses               #=> ['Draft', 'Pending Activation', 'Published', 'Archived']

Post.statuses_for_select          #=> [ ['Draft', :draft],
                                  #=>   ['Pending Activation', :pending],
                                  #=>   ['Published', :published],
                                  #=>   ['Archived', :archived] ]

Post.statuses_for_select(:sorted) #=> [ ['Archived', :archived] ],
                                  #=>   ['Draft', :draft],
                                  #=>   ['Pending Activation', :pending],
                                  #=>   ['Published', :published] ]

Clone this wiki locally