class NxtStateMachine::Transition::Factory

Attributes

block[R]
from[R]
name[R]
state_machine[R]
to[R]

Public Class Methods

new(name, from:, to:, state_machine:, &block) click to toggle source
# File lib/nxt_state_machine/transition/factory.rb, line 5
def initialize(name, from:, to:, state_machine:, &block)
  @name = name
  @from = state_machine.states.resolve!(from)
  @to = state_machine.states.resolve!(to)
  @state_machine = state_machine
  @block = block

  # TODO: Write a spec that verifies that transitions are unique
  ensure_states_exist
end

Public Instance Methods

build_transition(event, context, set_state_method, *args, **opts) click to toggle source

TODO: Probably would make sense if we could also define the event name to be passed in

> This way we could differentiate what event triggered the callback!!!

# File lib/nxt_state_machine/transition/factory.rb, line 21
def build_transition(event, context, set_state_method, *args, **opts)
  options = {
    from: from,
    to: to,
    state_machine: state_machine,
    context: context,
    event: event,
    set_state_method: set_state_method,
    arguments: args,
    options: opts
  }

  transition = Transition.new(event.name, **options)

  if block
    # if the transition takes a block we make it available through a proxy on the transition itself!
    transition.send(:block=, Proc.new do
      # if the transition block takes arguments we always pass the transition itself as the first argument
      # callbacks also get passed the transition object in case they take an argument and can access args and
      # options passed to the transition when invoked through that transition object
      if block.arity > 0
        args = [transition] + args
      end
      context.instance_exec(*args, **opts, &block)
    end)
  end

  transition.trigger
end

Private Instance Methods

ensure_states_exist() click to toggle source
# File lib/nxt_state_machine/transition/factory.rb, line 57
def ensure_states_exist
  raise NxtStateMachine::Errors::UnknownStateError, "No state with :#{from} registered" unless state_machine.states.key?(from.enum)
  raise NxtStateMachine::Errors::UnknownStateError, "No state with :#{to} registered" unless state_machine.states.key?(to.enum)
end