class GenericStateMachine::StateMachine
StateMachine
class
Attributes
current[R]
Public Class Methods
new(start_state)
click to toggle source
Create a new state machine @param [Symbol] start_state The starting state @raise GenericStateMachine::Errors::StateMachineError
# File state_machine/state_machine.rb, line 19 def initialize(start_state) raise GenericStateMachine::Errors::StateMachineError, "Can't create state machine w/o start state" if start_state.nil? || !start_state.is_a?(Symbol) initialize_hooks @transitions = {} @current = start_state end
Public Instance Methods
add(transition:)
click to toggle source
Add transition @param [GenericStateMachine::Transition] transition @raise GenericStateMachine::Errors::StateMachineError
# File state_machine/state_machine.rb, line 33 def add(transition:) raise GenericStateMachine::Errors::StateMachineError, "Invalid transition '#{transition}'" if transition.nil? || !transition.is_a?(GenericStateMachine::Transition) @transitions[transition.from] = transition end
next!()
click to toggle source
Switch current state @raise GenericStateMachine::Errors::StateMachineError
# File state_machine/state_machine.rb, line 44 def next! raise GenericStateMachine::Errors::StateMachineError, "No transition found for '#{@current}'" unless @transitions.key?(@current) # emit :before_transition emit! :before_transition @current = @transitions[@current].to # emit :after_transition emit! :after_transition end
register(hook:, handler:)
click to toggle source
Register a new hook @param [Symbol] hook @param [Object] handler The handler called when the hook is reached @raise GenericStateMachine::Errors::StateMachineError
# File state_machine/state_machine.rb, line 61 def register(hook:, handler:) raise GenericStateMachine::Errors::StateMachineError, "Invalid hook '#{hook}'" unless AVAILABLE_HOOKS.include?(hook) || hook.nil? || !hook.is_a?(Symbol) raise GenericStateMachine::Errors::StateMachineError, 'Invalid handler' if handler.nil? @hooks[hook] << handler end
Private Instance Methods
emit!(hook)
click to toggle source
Emit hook @param [Symbol] hook The hook to be emitted
# File state_machine/state_machine.rb, line 76 def emit!(hook) @hooks[hook].each(&:call) end
initialize_hooks()
click to toggle source
Initialize hooks hash
# File state_machine/state_machine.rb, line 83 def initialize_hooks @hooks = {} GenericStateMachine::AVAILABLE_HOOKS.each do |hook| @hooks[hook] = [] end end