Class: SimpleStateMachine::StateMachine

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

Overview

Defines the state machine used by the instance

Instance Method Summary collapse

Constructor Details

#initialize(subject) ⇒ StateMachine

Returns a new instance of StateMachine.



102
103
104
# File 'lib/simple_state_machine/simple_state_machine.rb', line 102

def initialize(subject)
  @subject = subject
end

Instance Method Details

#error_state(event_name, error) ⇒ Object

Returns the error state for the subject for event_name and error



113
114
115
116
# File 'lib/simple_state_machine/simple_state_machine.rb', line 113

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



107
108
109
110
# File 'lib/simple_state_machine/simple_state_machine.rb', line 107

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. Calls illegal_event_callback event_name if no next_state is found



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/simple_state_machine/simple_state_machine.rb', line 120

def transition(event_name)
  if to = next_state(event_name)
    begin
      result = yield
    rescue => e
      if error_state = error_state(event_name, 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