Class: ComposableStateMachine::Transitions

Inherits:
Object
  • Object
show all
Defined in:
lib/composable_state_machine/transitions.rb

Overview

Defines the transitions a state machine can make.

Instance Method Summary collapse

Constructor Details

#initialize(transitions = {}) ⇒ Transitions

Note:

While nil is a valid state to transition from, it is not a valid state to transition to.

Creates a ComposableStateMachine::Transitions object.

Parameters:

  • transitions (Hash<event, Hash<from_state, to_state>>) (defaults to: {})

    transitions Hash mapping events to a Hash from -> to state transitions



10
11
12
13
# File 'lib/composable_state_machine/transitions.rb', line 10

def initialize(transitions = {})
  @transitions_for = transitions
  validate_transitions
end

Instance Method Details

#eventsArray<Object>

Returns events for the machine.

Returns:

  • (Array<Object>)

    events for the machine



47
48
49
# File 'lib/composable_state_machine/transitions.rb', line 47

def events
  @transitions_for.keys
end

#on(event, transitions) ⇒ self

Adds to the transitions for an event.

Parameters:

  • event (Object)

    event causing the transition

  • transitions (Hash<from_state, to_state>)

    transitions to the added to the transitions for the event.

Returns:

  • (self)

    for chaining



21
22
23
24
25
26
27
# File 'lib/composable_state_machine/transitions.rb', line 21

def on(event, transitions)
  (@transitions_for[event] ||= {}).tap do |transitions_for_event|
    transitions_for_event.merge!(transitions)
    validate_transitions_for_event(event, transitions_for_event)
  end
  self
end

#statesArray<Object>

Returns the states of the machine.

Returns:

  • (Array<Object>)

    the states of the machine



52
53
54
# File 'lib/composable_state_machine/transitions.rb', line 52

def states
  events.map { |e| @transitions_for[e].to_a }.flatten.uniq
end

#transition(state, event) ⇒ Object?

Checks the transition map for a valid transition from a state given an event

Parameters:

  • state (Object)

    the state the machine is in

  • event (Object)

    event causing the transition

Returns:

  • (Object)

    new state for the machine, if a transition can occur

  • (nil)

    if a transition cannot happen with this event

Raises:



38
39
40
41
42
43
44
# File 'lib/composable_state_machine/transitions.rb', line 38

def transition(state, event)
  transitions_for_event = @transitions_for[event]
  unless transitions_for_event
    raise InvalidEvent.new("invalid event", event, state)
  end
  transitions_for_event[state]
end