Module: RailsStateMachine::Callbacks

Defined in:
lib/rails_state_machine/callbacks.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(model) ⇒ Object



4
5
6
7
# File 'lib/rails_state_machine/callbacks.rb', line 4

def included(model)
  register_callbacks(model)
  register_validations(model)
end

Instance Method Details

#flush_state_event_callbacks(name) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/rails_state_machine/callbacks.rb', line 65

def flush_state_event_callbacks(name)
  if @state_event_callbacks
    while (event = @state_event_callbacks[name].shift)
      event.public_send("run_#{name}", self)
    end
  end
end

#register_state_events_for_callbacksObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rails_state_machine/callbacks.rb', line 47

def register_state_events_for_callbacks
  @state_event_callbacks ||= {
    before_save: [],
    after_save: [],
    after_commit: []
  }
  state_machine_state_managers.each do |state_manager|
    if (next_event = state_manager.next_event)
      @state_event_callbacks[:before_save] << next_event
      @state_event_callbacks[:after_save] << next_event
      @state_event_callbacks[:after_commit] << next_event
      state_manager.next_event = nil
    end
  end

  true
end

#revert_statesObject



73
74
75
76
77
# File 'lib/rails_state_machine/callbacks.rb', line 73

def revert_states
  state_machine_state_managers.each do |state_manager|
    state_manager.revert
  end
end

#run_state_events_before_validationObject



39
40
41
42
43
44
45
# File 'lib/rails_state_machine/callbacks.rb', line 39

def run_state_events_before_validation
  # Since validations may be skipped, we will not register validation callbacks in @state_event_callbacks,
  # but call them explicitly when before_validation callbacks are triggered.
  state_machine_state_managers.each do |state_manager|
    state_manager.next_event&.run_before_validation(self)
  end
end

#set_state_from_state_eventObject



29
30
31
32
33
34
35
36
37
# File 'lib/rails_state_machine/callbacks.rb', line 29

def set_state_from_state_event
  state_machine_state_managers.each do |state_manager|
    next if state_manager.state_event.blank?

    unless state_manager.transition_to(state_manager.state_event)
      errors.add(:"#{state_manager.state_attribute}_event", :invalid)
    end
  end
end