Class: SimpleStateMachine::StateMachine

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_state_machine/state_machine.rb

Overview

Defines the state machine used by the instance

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject) ⇒ StateMachine

Returns a new instance of StateMachine.



10
11
12
# File 'lib/simple_state_machine/state_machine.rb', line 10

def initialize(subject)
  @subject = subject
end

Instance Attribute Details

#raised_errorObject (readonly)

Returns the value of attribute raised_error.



8
9
10
# File 'lib/simple_state_machine/state_machine.rb', line 8

def raised_error
  @raised_error
end

Instance Method Details

#error_state(event_name, error) ⇒ Object

Returns the error state for the subject for event_name and error



21
22
23
24
# File 'lib/simple_state_machine/state_machine.rb', line 21

def error_state(event_name, error)
  transition = transitions.select{|t| t.is_error_transition_for?(event_name, error) }.first
  transition ? transition.to : nil
end

#next_state(event_name) ⇒ Object

Returns the next state for the subject for event_name



15
16
17
18
# File 'lib/simple_state_machine/state_machine.rb', line 15

def next_state(event_name)
  transition = transitions.select{|t| t.is_transition_for?(event_name, @subject.send(state_method))}.first
  transition ? transition.to : nil
end

#transition(event_name) ⇒ Object

Transitions to the next state if next_state exists. When an error occurs, it uses the error to determine next state. If no next state can be determined it transitions to the default error state if defined, otherwise the error is re-raised. Calls illegal_event_callback event_name if no next_state is found



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/simple_state_machine/state_machine.rb', line 31

def transition(event_name)
  clear_raised_error
  if to = next_state(event_name)
    begin
      result = yield
    rescue => e
      error_state = error_state(event_name, e) ||
        state_machine_definition.default_error_state
      if error_state
        @raised_error = e
        @subject.send("#{state_method}=", error_state)
        return result
      else
        raise
      end
    end
    # TODO refactor out to AR module
    if defined?(::ActiveRecord) && @subject.is_a?(::ActiveRecord::Base)
      if @subject.errors.entries.empty?
        @subject.send("#{state_method}=", to)
        return true
      else
        return false
      end
    else
      @subject.send("#{state_method}=", to)
      return result
    end
  else
    illegal_event_callback event_name
  end
end