state_machines 0.202.0 → 0.301.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -443,7 +443,7 @@ module StateMachines
443
443
 
444
444
  default_message = "Expected sync execution of '#{event}' to change #{machine_name} from '#{initial_state}' to '#{expected_state}', but got '#{final_state}'"
445
445
 
446
- _sm_assert(result, "Event #{event} should return true on success")
446
+ _sm_assert(result, "Event #{event} should return the performed transition on success, but returned #{result.inspect}")
447
447
  _sm_assert(state_changed, "State should change from #{initial_state}")
448
448
  _sm_assert(correct_final_state, message || default_message)
449
449
  end
@@ -599,12 +599,211 @@ module StateMachines
599
599
  _sm_assert_empty(missing_methods, message || default_message)
600
600
  end
601
601
 
602
+ # === Refusal Reason Assertions ===
603
+
604
+ # The reasons an event can be refused for
605
+ #
606
+ # @see StateMachines::Event#refusal
607
+ REFUSAL_REASONS = %i[no_transition guard halted action_failed contended].freeze
608
+
609
+ # Assert that firing an event is refused, leaving the machine's state unchanged
610
+ #
611
+ # Fires the non-bang event method, which must return false. When a reason is
612
+ # given, the refusal recorded for the event must equal it.
613
+ #
614
+ # @param object [Object] The object with state machines
615
+ # @param event [Symbol] The event name (plain or namespace-qualified)
616
+ # @param reason [Symbol, nil] The expected refusal reason, or nil to accept any
617
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
618
+ # @param message [String, nil] Custom failure message
619
+ # @return [Symbol, nil] The recorded refusal reason
620
+ # @raise [ArgumentError] If the reason is not a known refusal reason
621
+ # @raise [AssertionError] If the event succeeds, changes the state, or is refused for another reason
622
+ #
623
+ # @example
624
+ # vehicle = Vehicle.new # parked
625
+ # assert_sm_refused(vehicle, :park) # Any reason
626
+ # assert_sm_refused(vehicle, :park, :no_transition) # Specific reason
627
+ # assert_sm_refused(vehicle, :enable, :guard, machine_name: :alarm_state)
628
+ def assert_sm_refused(object, event, reason = nil, machine_name: :state, message: nil)
629
+ _sm_validate_refusal_reason(reason) if reason
630
+ machine, event_obj = _sm_find_event(object, event, machine_name)
631
+
632
+ state_before = machine.read(object, :state)
633
+ result = object.public_send(event_obj.qualified_name)
634
+ state_after = machine.read(object, :state)
635
+ actual = event_obj.refusal(object)
636
+
637
+ unless result == false
638
+ outcome = result.is_a?(StateMachines::Transition) ? "it transitioned #{result.from_name.inspect} -> #{result.to_name.inspect}" : "it returned #{result.inspect}"
639
+ _sm_flunk(message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused, but #{outcome}")
640
+ end
641
+ _sm_assert(state_before == state_after,
642
+ message || "Expected a refused :#{event_obj.qualified_name} to leave #{machine.name} at #{state_before.inspect}, but it became #{state_after.inspect}")
643
+ if reason
644
+ _sm_assert_equal(reason, actual,
645
+ message || "Expected :#{event_obj.qualified_name} on #{machine.name} to be refused for #{reason.inspect}, but was refused for #{actual.inspect}")
646
+ end
647
+
648
+ actual
649
+ end
650
+
651
+ # Assert that the most recent attempt to fire an event was refused for the expected reason
652
+ #
653
+ # Reads the recorded refusal without firing the event.
654
+ #
655
+ # @param object [Object] The object with state machines
656
+ # @param event [Symbol] The event name (plain or namespace-qualified)
657
+ # @param expected_reason [Symbol] The expected refusal reason
658
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
659
+ # @param message [String, nil] Custom failure message
660
+ # @return [Symbol] The recorded refusal reason
661
+ # @raise [ArgumentError] If the reason is not a known refusal reason
662
+ # @raise [AssertionError] If the recorded reason differs
663
+ #
664
+ # @example
665
+ # vehicle.park
666
+ # assert_sm_refusal(vehicle, :park, :no_transition)
667
+ def assert_sm_refusal(object, event, expected_reason, machine_name: :state, message: nil)
668
+ _sm_validate_refusal_reason(expected_reason)
669
+ machine, event_obj = _sm_find_event(object, event, machine_name)
670
+ actual = event_obj.refusal(object)
671
+ default_message = "Expected the last :#{event_obj.qualified_name} on #{machine.name} to be refused for #{expected_reason.inspect}, but #{actual ? "it was refused for #{actual.inspect}" : 'no refusal was recorded'}"
672
+
673
+ _sm_assert_equal(expected_reason, actual, message || default_message)
674
+ actual
675
+ end
676
+
677
+ # Assert that the most recent attempt to fire an event recorded no refusal
678
+ #
679
+ # Reads the recorded refusal without firing the event. Passes after a
680
+ # success, or when the event was never fired.
681
+ #
682
+ # @param object [Object] The object with state machines
683
+ # @param event [Symbol] The event name (plain or namespace-qualified)
684
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
685
+ # @param message [String, nil] Custom failure message
686
+ # @return [void]
687
+ # @raise [AssertionError] If a refusal is recorded
688
+ #
689
+ # @example
690
+ # vehicle.ignite
691
+ # refute_sm_refusal(vehicle, :ignite)
692
+ def refute_sm_refusal(object, event, machine_name: :state, message: nil)
693
+ machine, event_obj = _sm_find_event(object, event, machine_name)
694
+ actual = event_obj.refusal(object)
695
+ default_message = "Expected no refusal for the last :#{event_obj.qualified_name} on #{machine.name}, but it was refused for #{actual.inspect}"
696
+
697
+ _sm_assert_nil(actual, message || default_message)
698
+ end
699
+ alias assert_sm_no_refusal refute_sm_refusal
700
+
701
+ # Assert that the bang event method raises StateMachines::InvalidTransition with the expected reason
702
+ #
703
+ # @param object [Object] The object with state machines
704
+ # @param event [Symbol] The event name (plain or namespace-qualified)
705
+ # @param expected_reason [Symbol] The expected StateMachines::InvalidTransition#reason
706
+ # @param machine_name [Symbol] The name of the state machine (defaults to :state)
707
+ # @param message [String, nil] Custom failure message
708
+ # @return [StateMachines::InvalidTransition] The raised error
709
+ # @raise [ArgumentError] If the reason is not a known refusal reason
710
+ # @raise [AssertionError] If nothing is raised or the reason differs
711
+ #
712
+ # @example
713
+ # assert_sm_raises_refusal(vehicle, :park, :no_transition)
714
+ def assert_sm_raises_refusal(object, event, expected_reason, machine_name: :state, message: nil)
715
+ _sm_validate_refusal_reason(expected_reason)
716
+ machine, event_obj = _sm_find_event(object, event, machine_name)
717
+ bang = "#{event_obj.qualified_name}!"
718
+
719
+ error = _sm_capture_error(StateMachines::InvalidTransition) { object.public_send(bang) }
720
+ _sm_flunk(message || "Expected #{bang} on #{machine.name} to raise StateMachines::InvalidTransition, but nothing was raised") unless error
721
+
722
+ _sm_assert_equal(expected_reason, error.reason,
723
+ message || "Expected #{bang} on #{machine.name} to be refused for #{expected_reason.inspect}, but was refused for #{error.reason.inspect}")
724
+ error
725
+ end
726
+
727
+ # Assert that firing events in parallel is refused with the expected reasons
728
+ #
729
+ # +fire_events+ must return false, and +fire_events!+ must raise
730
+ # StateMachines::InvalidParallelTransition whose #reasons equals the
731
+ # expected Hash. Only the events that caused the refusal carry a reason.
732
+ #
733
+ # @param object [Object] The object with state machines
734
+ # @param events [Array<Symbol>] The (qualified) event names to fire together
735
+ # @param expected_reasons [Hash{Symbol => Symbol}] The expected reason per event
736
+ # @param message [String, nil] Custom failure message
737
+ # @return [StateMachines::InvalidParallelTransition] The raised error
738
+ # @raise [ArgumentError] If a reason is not a known refusal reason
739
+ # @raise [AssertionError] If the events are not refused or the reasons differ
740
+ #
741
+ # @example
742
+ # assert_sm_parallel_refused(vehicle, %i[ignite enable_alarm], { enable_alarm: :no_transition })
743
+ def assert_sm_parallel_refused(object, events, expected_reasons, message: nil)
744
+ raise ArgumentError, "Expected reasons must be a Hash of event => reason, got #{expected_reasons.inspect}" unless expected_reasons.is_a?(Hash)
745
+
746
+ expected_reasons.each_value { |reason| _sm_validate_refusal_reason(reason) }
747
+ events = Array(events)
748
+
749
+ result = object.fire_events(*events)
750
+ _sm_flunk(message || "Expected fire_events(#{events.map(&:inspect).join(', ')}) to be refused, but it returned #{result.inspect}") unless result == false
751
+
752
+ error = _sm_capture_error(StateMachines::InvalidParallelTransition) { object.fire_events!(*events) }
753
+ _sm_flunk(message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to raise StateMachines::InvalidParallelTransition, but nothing was raised") unless error
754
+
755
+ _sm_assert_equal(expected_reasons, error.reasons,
756
+ message || "Expected fire_events!(#{events.map(&:inspect).join(', ')}) to be refused for #{expected_reasons.inspect}, but was refused for #{error.reasons.inspect}")
757
+ error
758
+ end
759
+
602
760
  # RSpec-style aliases for event triggering (for consistency with RSpec expectations)
603
761
  alias expect_to_trigger_event assert_sm_triggers_event
604
762
  alias have_triggered_event assert_sm_triggers_event
605
763
 
764
+ # RSpec-style aliases for refusal reasons
765
+ alias expect_to_be_refused assert_sm_refused
766
+ alias expect_refusal assert_sm_refusal
767
+ alias expect_no_refusal refute_sm_refusal
768
+ alias expect_to_raise_refusal assert_sm_raises_refusal
769
+ alias expect_parallel_refused assert_sm_parallel_refused
770
+
606
771
  private
607
772
 
773
+ # Finds the machine and its event, accepting the plain or the
774
+ # namespace-qualified event name, and raising when either is missing
775
+ def _sm_find_event(object, event, machine_name)
776
+ machine = object.class.state_machines[machine_name] if object.class.respond_to?(:state_machines)
777
+ unless machine
778
+ available = object.class.respond_to?(:state_machines) ? object.class.state_machines.keys : []
779
+ raise ArgumentError, "No state machine '#{machine_name}' found. Available machines: #{available.inspect}"
780
+ end
781
+
782
+ event_obj = machine.events[event.to_sym] || machine.events[event.to_sym, :qualified_name]
783
+ return [machine, event_obj] if event_obj
784
+
785
+ raise ArgumentError, "No event :#{event} found on machine :#{machine_name}. Available events: #{machine.events.map(&:qualified_name).inspect}"
786
+ end
787
+
788
+ # Raises a descriptive ArgumentError for an unknown refusal reason, so a
789
+ # typo in the expectation is not reported as a failed refusal
790
+ def _sm_validate_refusal_reason(reason)
791
+ return if REFUSAL_REASONS.include?(reason)
792
+
793
+ suggestion = DidYouMean::SpellChecker.new(dictionary: REFUSAL_REASONS).correct(reason.to_s).first if defined?(DidYouMean::SpellChecker)
794
+ hint = suggestion ? " Did you mean #{suggestion.inspect}?" : ''
795
+ raise ArgumentError, "Unknown refusal reason #{reason.inspect}.#{hint} Valid reasons: #{REFUSAL_REASONS.inspect}"
796
+ end
797
+
798
+ # Runs the block and returns the error of the given class it raised, or
799
+ # nil when it raised nothing; other errors propagate
800
+ def _sm_capture_error(error_class)
801
+ yield
802
+ nil
803
+ rescue error_class => e
804
+ e
805
+ end
806
+
608
807
  # Finds the can_<event>? method for the event, trying both the default and
609
808
  # namespaced naming patterns, and raising when neither exists
610
809
  def _sm_find_can_method(object, event, machine_name)
@@ -653,6 +852,16 @@ module StateMachines
653
852
  end
654
853
  end
655
854
 
855
+ def _sm_assert_nil(value, message)
856
+ if defined?(::Minitest)
857
+ assert_nil value, message
858
+ elsif defined?(::RSpec)
859
+ expect(value).to be_nil, message
860
+ else
861
+ raise message unless value.nil?
862
+ end
863
+ end
864
+
656
865
  def _sm_assert_empty(collection, message)
657
866
  if defined?(::Minitest)
658
867
  assert_empty collection, message
@@ -35,6 +35,14 @@ module StateMachines
35
35
  # Whether the transition is only existing temporarily for the object
36
36
  attr_writer :transient
37
37
 
38
+ # Why the most recent perform of this transition was refused.
39
+ #
40
+ # @return [:halted, :action_failed, :contended, nil] the refusal reason, or
41
+ # nil if the transition succeeded or was refused only because another
42
+ # transition in the same collection was
43
+ # @see StateMachines::Event#refusal for the meaning of each reason
44
+ attr_accessor :refusal
45
+
38
46
  # Creates a new, specific transition
39
47
  def initialize(object, machine, event, from_name, to_name, read_state = true) # :nodoc:
40
48
  @object = object
@@ -161,6 +169,9 @@ module StateMachines
161
169
  # transition.perform(Time.now) # => Passes in additional arguments and runs the +save+ action
162
170
  # transition.perform(Time.now, false) # => Passes in additional arguments and only sets the state attribute
163
171
  # transition.perform(Time.now, run_action: false) # => Passes in additional arguments and only sets the state attribute
172
+ #
173
+ # @return [StateMachines::Transition, false] this transition when it
174
+ # succeeds, false when it is refused (see {#refusal})
164
175
  def perform(*args)
165
176
  run_action = case args.last
166
177
  in true | false
@@ -174,7 +185,7 @@ module StateMachines
174
185
  self.args = args
175
186
 
176
187
  # Run the transition
177
- !!TransitionCollection.new([self], { use_transactions: machine.use_transactions, actions: run_action }).perform
188
+ TransitionCollection.new([self], { use_transactions: machine.use_transactions, actions: run_action }).perform ? self : false
178
189
  end
179
190
 
180
191
  # Runs a block within a transaction for the object being transitioned.
@@ -287,6 +298,9 @@ module StateMachines
287
298
  # the state has already been persisted
288
299
  def reset
289
300
  @before_run = @persisted = @after_run = false
301
+ # Kill so ensure blocks in paused callbacks still run (CRuby only:
302
+ # TruffleRuby lacks Fiber#kill, JRuby's doesn't wait for ensure)
303
+ @paused_fiber.kill if RUBY_ENGINE == 'ruby' && @paused_fiber&.alive? && !@paused_fiber.equal?(Fiber.current)
290
304
  @paused_fiber = nil
291
305
  @resuming = false
292
306
  @continuation_block = nil
@@ -504,7 +518,7 @@ module StateMachines
504
518
  #
505
519
  # Once the callbacks are run, they cannot be run again until this transition
506
520
  # is reset.
507
- def before(complete = true, index = 0, &block)
521
+ def before(complete = true, index = 0, &)
508
522
  return if @before_run
509
523
 
510
524
  callback = machine.callbacks[:before][index]
@@ -519,7 +533,7 @@ module StateMachines
519
533
  # * The block succeeds, but after callbacks are disabled (in which
520
534
  # case a continuation is stored for later execution)
521
535
  callback.call(object, context, self) do
522
- before(complete, index + 1, &block)
536
+ before(complete, index + 1, &)
523
537
 
524
538
  pause if @success && !complete
525
539
 
@@ -531,11 +545,11 @@ module StateMachines
531
545
  # Normal before callback
532
546
  callback.call(object, context, self)
533
547
  # Continue with next callback
534
- before(complete, index + 1, &block)
548
+ before(complete, index + 1, &)
535
549
  end
536
550
  else
537
551
  # Skip to next callback if it doesn't match
538
- before(complete, index + 1, &block)
552
+ before(complete, index + 1, &)
539
553
  end
540
554
  else
541
555
  # No more callbacks, execute the action block if at the end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StateMachines
4
+ # A hold on one of an object's machine attributes, granted for the duration
5
+ # of a single TransitionCollection#perform
6
+ class TransitionClaim
7
+ # The authority a perform holds over the attributes it claimed. The fibers
8
+ # a perform spawns inherit its authority, which is retired once that
9
+ # perform ends.
10
+ class Owner
11
+ def initialize
12
+ @active = true
13
+ end
14
+
15
+ def active?
16
+ @active
17
+ end
18
+
19
+ def retire
20
+ @active = false
21
+ end
22
+ end
23
+
24
+ CLAIMS_VARIABLE = :@_state_machine_transition_claims
25
+ OWNER_KEY = :state_machines_transition_owner
26
+ LOCK = Thread::Mutex.new
27
+
28
+ class << self
29
+ # Claims an attribute for every given transition whose machine runs in
30
+ # async mode, ordered by attribute so that collections over the same
31
+ # attributes claim them in the same order.
32
+ #
33
+ # Returns the granted claims, or nil when an attribute is held by another
34
+ # active owner or has left the transition's source state. Every exit
35
+ # that does not grant the whole set - a refusal, an exception, a throw -
36
+ # releases the claims it took.
37
+ #
38
+ # @param transitions [Array<StateMachines::Transition>] the transitions
39
+ # to claim attributes for
40
+ # @yieldparam transition [StateMachines::Transition] the transition whose
41
+ # attribute could not be claimed, when the claim is refused
42
+ # @return [Array<StateMachines::TransitionClaim>, nil]
43
+ def claim(transitions)
44
+ claimable = transitions.select { |transition| transition.machine.async_mode_enabled? }
45
+ granted = []
46
+ admitted = false
47
+
48
+ begin
49
+ admitted = claimable.sort_by { |transition| transition.attribute.to_s }.all? do |transition|
50
+ next true if hold(transition, granted) && at_source?(transition)
51
+
52
+ yield(transition) if block_given?
53
+ false
54
+ end
55
+
56
+ granted if admitted
57
+ ensure
58
+ release(granted) unless admitted
59
+ end
60
+ end
61
+
62
+ # Releases the claims granted by .claim
63
+ def release(claims)
64
+ claims.reverse_each(&:release)
65
+ end
66
+
67
+ private
68
+
69
+ # Takes the transition's attribute, appending the claim to +granted+ as it
70
+ # is taken. Returns nil when another active owner holds the attribute.
71
+ def hold(transition, granted)
72
+ previous_owner = Fiber[OWNER_KEY]
73
+ owner = previous_owner&.active? ? previous_owner : Owner.new
74
+ object = transition.object
75
+ attribute = transition.attribute
76
+
77
+ LOCK.synchronize do
78
+ claims = claims_for(object)
79
+ holder = claims[attribute]
80
+ next unless holder.nil? || !holder.active? || holder.equal?(owner)
81
+
82
+ claim = new(claims, attribute, owner, previous_owner, !holder.equal?(owner))
83
+ granted << claim
84
+ claims[attribute] = owner
85
+ Fiber[OWNER_KEY] = owner
86
+ claim
87
+ end
88
+ end
89
+
90
+ def at_source?(transition)
91
+ transition.machine.states.match!(transition.object).name == transition.from_name
92
+ end
93
+
94
+ def claims_for(object)
95
+ object.instance_variable_get(CLAIMS_VARIABLE) || object.instance_variable_set(CLAIMS_VARIABLE, {})
96
+ end
97
+ end
98
+
99
+ def initialize(claims, attribute, owner, previous_owner, held) # :nodoc:
100
+ @claims = claims
101
+ @attribute = attribute
102
+ @owner = owner
103
+ @previous_owner = previous_owner
104
+ @held = held
105
+ end
106
+
107
+ # Gives up this claim, retiring its owner's authority when the claim
108
+ # created it
109
+ def release
110
+ Fiber[OWNER_KEY] = @previous_owner
111
+
112
+ LOCK.synchronize do
113
+ @owner.retire unless @owner.equal?(@previous_owner)
114
+ @claims.delete(@attribute) if @held
115
+ end
116
+ end
117
+ end
118
+ end
@@ -59,7 +59,77 @@ module StateMachines
59
59
  #
60
60
  # If a block is passed to this method, that block will be called instead
61
61
  # of invoking each transition's action.
62
- def perform(&block)
62
+ #
63
+ # When the collection is refused, each transition that caused it carries
64
+ # the reason in {StateMachines::Transition#refusal}, and the reason is
65
+ # recorded for its event on the object. The outcome of this attempt is
66
+ # recorded however it ends: a success or an exception raised before any
67
+ # outcome (e.g. by a callback) clears the reasons left by an earlier
68
+ # attempt.
69
+ #
70
+ # When the action fails because an event attribute it performed was
71
+ # refused (a collection nested inside the action, as the ORM integrations
72
+ # run around save), the transitions carry that inner reason instead of
73
+ # :action_failed.
74
+ #
75
+ # @return [Object, false] the action's result, or whether every transition
76
+ # succeeded
77
+ # @see StateMachines::Event#refusal
78
+ def perform(&)
79
+ each { |transition| transition.refusal = nil }
80
+ claims = TransitionClaim.claim(self) { |transition| transition.refusal = :contended }
81
+ return false unless claims
82
+
83
+ result = perform_transitions(&)
84
+ assign_refusals unless success?
85
+ result
86
+ ensure
87
+ record_refusals
88
+ TransitionClaim.release(claims) if claims
89
+ end
90
+
91
+ class << self
92
+ # Reports the reason an event attribute performed inside an action was
93
+ # refused to the innermost collection running that action on the same
94
+ # object, which then carries it instead of :action_failed if the action
95
+ # fails.
96
+ #
97
+ # @api private
98
+ # @param object [Object] the object the action runs on
99
+ # @param reason [Symbol, nil] the inner refusal reason
100
+ # @return [void]
101
+ def report_nested_refusal(object, reason)
102
+ return unless reason
103
+
104
+ running = Thread.current[RUNNING_ACTIONS_KEY]&.reverse_each&.find { |collection| collection.object.equal?(object) }
105
+ running&.nested_refusal ||= reason
106
+ end
107
+ end
108
+
109
+ # The fiber-local stack of collections whose actions are running
110
+ RUNNING_ACTIONS_KEY = :state_machines_running_actions
111
+
112
+ # The reason an event attribute performed inside this collection's action
113
+ # was refused (see .report_nested_refusal)
114
+ #
115
+ # @api private
116
+ # @return [Symbol, nil]
117
+ attr_accessor :nested_refusal
118
+
119
+ # Gets the object being transitioned
120
+ #
121
+ # @return [Object]
122
+ def object
123
+ first.object
124
+ end
125
+
126
+ protected
127
+
128
+ attr_reader :results # :nodoc:
129
+
130
+ private
131
+
132
+ def perform_transitions(&)
63
133
  reset
64
134
 
65
135
  if valid?
@@ -69,10 +139,11 @@ module StateMachines
69
139
  transition.machine.write(object, :event_transition, transition)
70
140
  end
71
141
 
142
+ @actions_run = true
72
143
  run_actions
73
144
  else
74
145
  within_transaction do
75
- catch(:halt) { run_callbacks(&block) }
146
+ catch(:halt) { run_callbacks(&) }
76
147
  rollback unless success?
77
148
  end
78
149
  end
@@ -85,12 +156,6 @@ module StateMachines
85
156
  end
86
157
  end
87
158
 
88
- protected
89
-
90
- attr_reader :results # :nodoc:
91
-
92
- private
93
-
94
159
  # Is this a valid set of transitions? If the collection was creating with
95
160
  # any +false+ values for transitions, then the the collection will be
96
161
  # marked as invalid.
@@ -106,11 +171,6 @@ module StateMachines
106
171
  @success
107
172
  end
108
173
 
109
- # Gets the object being transitioned
110
- def object
111
- first.object
112
- end
113
-
114
174
  # Gets the list of actions to run. If configured to skip actions, then
115
175
  # this will return an empty collection.
116
176
  def actions
@@ -129,6 +189,36 @@ module StateMachines
129
189
  def reset
130
190
  @results = {}
131
191
  @success = false
192
+ @actions_run = false
193
+ @halted_by = nil
194
+ @nested_refusal = nil
195
+ end
196
+
197
+ # Assigns the reason this collection was refused to the transitions that
198
+ # caused it. A reason already assigned by a collection nested inside the
199
+ # action (an action hook performing the same transitions) is kept, since
200
+ # it knows why the action failed; so is a reason reported by an event
201
+ # attribute refused inside the action (see .report_nested_refusal).
202
+ #
203
+ # @return [void]
204
+ def assign_refusals
205
+ return if any?(&:refusal)
206
+
207
+ if @actions_run
208
+ reason = nested_refusal || :action_failed
209
+ each { |transition| transition.refusal = reason }
210
+ elsif @halted_by
211
+ @halted_by.refusal = :halted
212
+ end
213
+ end
214
+
215
+ # Records each transition's refusal (or its absence) for its event on the
216
+ # object
217
+ #
218
+ # @return [void]
219
+ # @see StateMachines::Event#record_refusal
220
+ def record_refusals
221
+ each { |transition| transition.machine.events.fetch(transition.event).record_refusal(transition.object, transition.refusal) }
132
222
  end
133
223
 
134
224
  # Runs each transition's callbacks recursively. Once all before callbacks
@@ -136,14 +226,14 @@ module StateMachines
136
226
  # configured actions will be run.
137
227
  #
138
228
  # If any transition fails to run its callbacks, :halt will be thrown.
139
- def run_callbacks(index = 0, &block)
229
+ def run_callbacks(index = 0, &)
140
230
  if (transition = self[index])
141
231
  # Pass through any options that affect callback execution (e.g., fiber: false)
142
232
  callback_options = { after: !skip_after }
143
233
  callback_options[:fiber] = options[:fiber] if options.key?(:fiber)
144
234
 
145
235
  callback_result = transition.run_callbacks(callback_options) do
146
- run_callbacks(index + 1, &block)
236
+ run_callbacks(index + 1, &)
147
237
  { result: results[transition.action], success: success? }
148
238
  end
149
239
 
@@ -151,10 +241,16 @@ module StateMachines
151
241
  # consider it successful (the pause was intentional)
152
242
  @success = true if skip_after && transition.paused?
153
243
 
154
- throw :halt unless callback_result
244
+ unless callback_result
245
+ # The innermost transition to halt is the one that caused it; the
246
+ # ones wrapping it halt as a consequence
247
+ @halted_by ||= transition
248
+ throw :halt
249
+ end
155
250
  else
156
251
  persist
157
- run_actions(&block)
252
+ @actions_run = true
253
+ run_actions(&)
158
254
  end
159
255
  end
160
256
 
@@ -189,10 +285,27 @@ module StateMachines
189
285
  # Wraps the given block with a rescue handler so that any exceptions that
190
286
  # occur will automatically result in the transition rolling back any changes
191
287
  # that were made to the object involved.
288
+ #
289
+ # An action that raises (e.g. ActiveRecord's save!) has failed, so the
290
+ # transitions are refused with :action_failed before the exception
291
+ # propagates.
292
+ #
293
+ # While the block runs, the collection is registered as running its
294
+ # action on the object, so that event attributes refused inside it can
295
+ # report their reason (see .report_nested_refusal).
296
+ #
297
+ # @raise [StandardError] whatever the block raised, after the rollback
192
298
  def catch_exceptions
193
- yield
299
+ running = (Thread.current[RUNNING_ACTIONS_KEY] ||= [])
300
+ running.push(self)
301
+ begin
302
+ yield
303
+ ensure
304
+ running.pop
305
+ end
194
306
  rescue StandardError
195
307
  rollback
308
+ each { |transition| transition.refusal ||= :action_failed }
196
309
  raise
197
310
  end
198
311
 
@@ -217,6 +330,17 @@ module StateMachines
217
330
  super(transitions, { use_transactions: false, actions: false }.merge(options))
218
331
  end
219
332
 
333
+ # Performs the event attributes' transitions around the action. When
334
+ # they are refused, the reason is reported to the collection running the
335
+ # action, if any (see TransitionCollection.report_nested_refusal).
336
+ #
337
+ # @return [Object, false] see TransitionCollection#perform
338
+ def perform(&)
339
+ result = super
340
+ TransitionCollection.report_nested_refusal(object, find(&:refusal)&.refusal) unless empty? || success?
341
+ result
342
+ end
343
+
220
344
  private
221
345
 
222
346
  # Hooks into running transition callbacks so that event / event transition
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module StateMachines
4
- VERSION = '0.202.0'
4
+ VERSION = '0.301.0'
5
5
  end