Module: StateGate::Engine::Transitioner

Included in:
StateGate::Engine
Defined in:
lib/state_gate/engine/transitioner.rb

Overview

Description

Provides transition helper methods for StateGate::Engine.

Instance Method Summary collapse

Instance Method Details

#assert_valid_transition!(current_state = nil, new_state = nil) ⇒ true

Returns if a transition is allowed.

Examples:

.assert_valid_transition!(:pending, :active) #=> true
.assert_valid_transition!(:active, :pending) #=> ArgumentError

Returns:

  • (true)

    if a transition is allowed

Raises:

  • (ArgumentError)

    if a transition is invalid



74
75
76
77
78
79
80
81
82
83
# File 'lib/state_gate/engine/transitioner.rb', line 74

def assert_valid_transition!(current_state = nil, new_state = nil)
  from_state = assert_valid_state!(current_state)
  to_state   = assert_valid_state!(new_state)

  return true if to_state == from_state
  return true if to_state.to_s.start_with?('force_')
  return true if @states[from_state][:transitions_to].include?(to_state)

  _aerr(:invalid_state_transition_err, from: from_state, to: to_state, kattr: true)
end

#transitionless?Boolean

Returns true if every state can transition to every other state, rendering transitions pointless.

Examples:

.transitionless?  #=> true

Returns:

  • (Boolean)

    true if every state can transition to every other state, rendering transitions pointless.



20
21
22
# File 'lib/state_gate/engine/transitioner.rb', line 20

def transitionless?
  !!@transitionless
end

#transitionsHash

Returns of states and allowed transitions.

Examples:

.transitions  #=> { pending:   [:active],
                     ativive:   [:suspended, :archived],
                     suspended: [:active, :archived],
                     archived:  [] }

Returns:

  • (Hash)

    of states and allowed transitions.



36
37
38
39
40
41
42
# File 'lib/state_gate/engine/transitioner.rb', line 36

def transitions
  @transitions ||= begin
    transitions = {}
    @states.each { |k, v| transitions[k] = v[:transitions_to] } # rubocop:disable Layout/ExtraSpacing
    transitions
  end
end

#transitions_for_state(state) ⇒ Array

Returns of allowed transitions for the given state.

Examples:

.transitions_for_state(:active) #=> [:suspended, :archived]

Parameters:

  • state (Symbol, String)

    the state name

Returns:

  • (Array)

    of allowed transitions for the given state



56
57
58
59
# File 'lib/state_gate/engine/transitioner.rb', line 56

def transitions_for_state(state)
  state_name = assert_valid_state!(state)
  transitions[state_name]
end