Module: NxtStateMachine::AttrAccessor::ClassMethods

Defined in:
lib/nxt_state_machine/integrations/attr_accessor.rb

Instance Method Summary collapse

Instance Method Details

#state_machine(name = :default, state_attr: :state, target: nil, &config) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
# File 'lib/nxt_state_machine/integrations/attr_accessor.rb', line 4

def state_machine(name = :default, state_attr: :state, target: nil, &config)
  machine = super(
    name,
    state_attr: state_attr,
    target: target,
    &config
  )

  machine.get_state_with do |target|
    if target.send(state_attr).nil?
      target.send("#{state_attr}=", initial_state.enum)
    end

    target.send(state_attr)
  end

  machine.set_state_with do |target, transition|
    transition.run_before_callbacks
    result = set_state(target, transition, state_attr)
    transition.run_after_callbacks

    transition.run_success_callbacks || result
  rescue StandardError => error
    target.send("#{state_attr}=", transition.from.enum)

    if error.is_a?(NxtStateMachine::Errors::TransitionHalted)
      false
    else
      raise
    end
  end

  machine.set_state_with! do |target, transition|
    transition.run_before_callbacks
    result = set_state(target, transition, state_attr)
    transition.run_after_callbacks

    transition.run_success_callbacks || result
  rescue StandardError
    target.send("#{state_attr}=", transition.from.enum)
    raise
  end

  machine
end