Class: NxtStateMachine::Transition::Factory

Inherits:
Object
  • Object
show all
Includes:
Interface
Defined in:
lib/nxt_state_machine/transition/factory.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Interface

#id, #transitions_from_to?

Constructor Details

#initialize(name, from:, to:, state_machine:, &block) ⇒ Factory

Returns a new instance of Factory.



5
6
7
8
9
10
11
12
13
14
# 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

Instance Attribute Details

#fromObject (readonly)

Returns the value of attribute from.



16
17
18
# File 'lib/nxt_state_machine/transition/factory.rb', line 16

def from
  @from
end

#nameObject (readonly)

Returns the value of attribute name.



16
17
18
# File 'lib/nxt_state_machine/transition/factory.rb', line 16

def name
  @name
end

#toObject (readonly)

Returns the value of attribute to.



16
17
18
# File 'lib/nxt_state_machine/transition/factory.rb', line 16

def to
  @to
end

Instance Method Details

#build_transition(event, context, set_state_method, *args, **opts) ⇒ Object

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!!!



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 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