class ActionInteractor::State

Action Interactor State

Simple state machine for general purpose. You can declare STATES / TRANSITIONS in subclasses for customizing the behavior. See also `ActionInteractor::ExecutionState`

Constants

STATES

Define default states

TRANSITIONS

Define default transitions key: target state, value: original states

Attributes

state[R]

Public Class Methods

new(initial_state=nil) click to toggle source
# File lib/action_interactor/state.rb, line 22
def initialize(initial_state=nil)
  @state = initial_state || default_state
end
states() click to toggle source

Available states for the class

# File lib/action_interactor/state.rb, line 48
def self.states
  self::STATES
end
transitions() click to toggle source

Available transitions for the class

# File lib/action_interactor/state.rb, line 53
def self.transitions
  self::TRANSITIONS
end

Public Instance Methods

default_state() click to toggle source

Default initial state (You can override in subclasses.)

# File lib/action_interactor/state.rb, line 28
def default_state
  :initial
end
method_missing(method_name, *args) click to toggle source
Calls superclass method
# File lib/action_interactor/state.rb, line 57
def method_missing(method_name, *args)
  name = method_name.to_s
  # Returns true if state_name is the same as current state
  if status_method_with_suffix?(name, "?")
    return state == name.chop.to_sym
  end

  # Set current state to the state_name, otherwise raises error
  if status_method_with_suffix?(name, "!")
    state_name = name.chop.to_sym
    unless valid_transition?(state_name)
      raise TransitionError.new("Could not change state :#{state_name} from :#{state}")
    end
    @state = state_name
    return
  end

  super
end
states() click to toggle source

Available states for the instance

# File lib/action_interactor/state.rb, line 38
def states
  self.class.states
end
transitions() click to toggle source

Avaiolable transitions for the instance's states

# File lib/action_interactor/state.rb, line 43
def transitions
  self.class.transitions
end
valid_transition?(target_state) click to toggle source

Returns true if transition to target_state from current state

# File lib/action_interactor/state.rb, line 33
def valid_transition?(target_state)
  transitions[target_state].include?(state)
end

Private Instance Methods

status_method_with_suffix?(method_name, suffix) click to toggle source
# File lib/action_interactor/state.rb, line 79
def status_method_with_suffix?(method_name, suffix)
  return false unless method_name.end_with?(suffix)
  states.include?(method_name.chop.to_sym)
end