class Machina

Constants

EVENT
InvalidEventError
InvalidStateChangeError

Attributes

events[R]
state[R]

Public Class Methods

new(initial_state) click to toggle source

Initializes Machina

@param initial_state [Symbol] the initial state of the state machine @return [Machina] the initialized Machina

# File lib/machina.rb, line 16
def initialize(initial_state)
  @state = initial_state
  @events = Hash.new { |h, k| h[k] = [] }
end

Public Instance Methods

[]=(key, states) click to toggle source

Defines the list of possible events and their transitions

@param key [Symbol] the event name @param states [Hash] the event transitions @return [void]

# File lib/machina.rb, line 88
def []=(key, states)
  events[key] = states
end
on() click to toggle source

Defines the list of possible callbacks when an event is triggered

@return [Hash]

# File lib/machina.rb, line 70
def on
  @on ||= Hash.new(&EVENT)
end
trigger(event, *args) click to toggle source

Triggers an event.

@param event [Symbol] the event to trigger @param args [Array<Object>] the objects that the callback will receive @return [void]

# File lib/machina.rb, line 27
def trigger(event, *args)
  return unless trigger?(event)

  Array(events[event][state]).each do |candidate_state|
    begin
      self.when[candidate_state].call(*args)
    rescue StandardError
      break
    end

    @state = candidate_state
  end

  on[event].call(*args)
end
trigger!(event, *args) click to toggle source

Triggers an event and raises on error.

@param event [Symbol] the event to trigger @param args [Array<Object>] the objects that the callback will receive @return [void]

# File lib/machina.rb, line 49
def trigger!(event, *args)
  raise InvalidStateChangeError, "Event #{event} missing #{state} step" unless trigger?(event)

  trigger(event, *args)
end
trigger?(event) click to toggle source

Checks if an event can be triggered

@param event [Symbol] the event to trigger @return [Boolean] the chance posibility

# File lib/machina.rb, line 60
def trigger?(event)
  raise InvalidEventError, "Event #{event} not found." unless events.key?(event)

  events[event].key?(state)
end
when() click to toggle source

Defines the list of possible callbacks when a state is reached

@return [Hash]

# File lib/machina.rb, line 78
def when
  @when ||= Hash.new(&EVENT)
end