state_machines 0.202.0 → 0.305.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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +226 -125
  3. data/lib/state_machines/branch.rb +56 -22
  4. data/lib/state_machines/callback.rb +28 -8
  5. data/lib/state_machines/core.rb +1 -0
  6. data/lib/state_machines/error.rb +50 -2
  7. data/lib/state_machines/eval_helpers.rb +31 -18
  8. data/lib/state_machines/event.rb +187 -4
  9. data/lib/state_machines/event_collection.rb +6 -1
  10. data/lib/state_machines/extensions.rb +22 -0
  11. data/lib/state_machines/helper_module.rb +1 -0
  12. data/lib/state_machines/machine/action_hooks.rb +13 -10
  13. data/lib/state_machines/machine/callbacks.rb +15 -0
  14. data/lib/state_machines/machine/class_methods.rb +34 -3
  15. data/lib/state_machines/machine/configuration.rb +12 -8
  16. data/lib/state_machines/machine/event_methods.rb +5 -0
  17. data/lib/state_machines/machine/helper_generators.rb +26 -11
  18. data/lib/state_machines/machine/state_methods.rb +4 -3
  19. data/lib/state_machines/machine/utilities.rb +25 -1
  20. data/lib/state_machines/machine.rb +62 -3
  21. data/lib/state_machines/machine_collection.rb +7 -6
  22. data/lib/state_machines/macro_methods.rb +4 -4
  23. data/lib/state_machines/node_collection.rb +26 -23
  24. data/lib/state_machines/path.rb +1 -0
  25. data/lib/state_machines/path_collection.rb +1 -0
  26. data/lib/state_machines/state.rb +66 -31
  27. data/lib/state_machines/state_collection.rb +10 -2
  28. data/lib/state_machines/state_context.rb +7 -1
  29. data/lib/state_machines/stdio_renderer.rb +8 -6
  30. data/lib/state_machines/syntax_validator.rb +3 -3
  31. data/lib/state_machines/test_helper.rb +309 -259
  32. data/lib/state_machines/transition.rb +136 -230
  33. data/lib/state_machines/transition_claim.rb +119 -0
  34. data/lib/state_machines/transition_collection.rb +147 -31
  35. data/lib/state_machines/version.rb +1 -1
  36. metadata +8 -15
  37. data/lib/state_machines/async_mode/async_event_extensions.rb +0 -49
  38. data/lib/state_machines/async_mode/async_events.rb +0 -286
  39. data/lib/state_machines/async_mode/async_machine.rb +0 -60
  40. data/lib/state_machines/async_mode/async_transition_collection.rb +0 -136
  41. data/lib/state_machines/async_mode/thread_safe_state.rb +0 -47
  42. data/lib/state_machines/async_mode.rb +0 -64
  43. data/lib/state_machines/machine/async_extensions.rb +0 -88
  44. data/lib/state_machines/machine/validation.rb +0 -39
@@ -34,17 +34,17 @@ module StateMachines
34
34
  attributes = map(&:attribute).uniq
35
35
  raise ArgumentError, 'Cannot perform multiple transitions in parallel for the same state machine attribute' if attributes.length != length
36
36
 
37
- StateMachines::OptionsValidator.assert_valid_keys!(options, :actions, :after, :use_transactions, :fiber)
37
+ StateMachines::OptionsValidator.assert_valid_keys!(options, :actions, :after, :use_transactions)
38
38
  options = { actions: true, after: true, use_transactions: true }.merge(options)
39
39
  @skip_actions = !options[:actions]
40
40
  @skip_after = !options[:after]
41
41
  @use_transactions = options[:use_transactions]
42
42
  @options = options
43
43
 
44
- # Reset transitions when creating a new collection
45
- # But preserve paused transitions to allow resuming
44
+ # Reset transitions when creating a new collection, except those a
45
+ # preview run started, which this collection continues
46
46
  each do |transition|
47
- transition.reset unless transition.paused?
47
+ transition.reset unless transition.previewed?
48
48
  end
49
49
  end
50
50
 
@@ -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 stack (Thread.current, so per fiber) 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,25 +226,23 @@ 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
- # Pass through any options that affect callback execution (e.g., fiber: false)
142
- callback_options = { after: !skip_after }
143
- callback_options[:fiber] = options[:fiber] if options.key?(:fiber)
144
-
145
- callback_result = transition.run_callbacks(callback_options) do
146
- run_callbacks(index + 1, &block)
231
+ callback_result = transition.run_callbacks(after: !skip_after) do
232
+ run_callbacks(index + 1, &)
147
233
  { result: results[transition.action], success: success? }
148
234
  end
149
235
 
150
- # If we're skipping after callbacks and the transition is paused,
151
- # consider it successful (the pause was intentional)
152
- @success = true if skip_after && transition.paused?
153
-
154
- throw :halt unless callback_result
236
+ unless callback_result
237
+ # The innermost transition to halt is the one that caused it; the
238
+ # ones wrapping it halt as a consequence
239
+ @halted_by ||= transition
240
+ throw :halt
241
+ end
155
242
  else
156
243
  persist
157
- run_actions(&block)
244
+ @actions_run = true
245
+ run_actions(&)
158
246
  end
159
247
  end
160
248
 
@@ -189,10 +277,27 @@ module StateMachines
189
277
  # Wraps the given block with a rescue handler so that any exceptions that
190
278
  # occur will automatically result in the transition rolling back any changes
191
279
  # that were made to the object involved.
280
+ #
281
+ # An action that raises (e.g. ActiveRecord's save!) has failed, so the
282
+ # transitions are refused with :action_failed before the exception
283
+ # propagates.
284
+ #
285
+ # While the block runs, the collection is registered as running its
286
+ # action on the object, so that event attributes refused inside it can
287
+ # report their reason (see .report_nested_refusal).
288
+ #
289
+ # @raise [StandardError] whatever the block raised, after the rollback
192
290
  def catch_exceptions
193
- yield
291
+ running = (Thread.current[RUNNING_ACTIONS_KEY] ||= [])
292
+ running.push(self)
293
+ begin
294
+ yield
295
+ ensure
296
+ running.pop
297
+ end
194
298
  rescue StandardError
195
299
  rollback
300
+ each { |transition| transition.refusal ||= :action_failed }
196
301
  raise
197
302
  end
198
303
 
@@ -217,6 +322,17 @@ module StateMachines
217
322
  super(transitions, { use_transactions: false, actions: false }.merge(options))
218
323
  end
219
324
 
325
+ # Performs the event attributes' transitions around the action. When
326
+ # they are refused, the reason is reported to the collection running the
327
+ # action, if any (see TransitionCollection.report_nested_refusal).
328
+ #
329
+ # @return [Object, false] see TransitionCollection#perform
330
+ def perform(&)
331
+ result = super
332
+ TransitionCollection.report_nested_refusal(object, find(&:refusal)&.refusal) unless empty? || success?
333
+ result
334
+ end
335
+
220
336
  private
221
337
 
222
338
  # 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.305.0'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: state_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.202.0
4
+ version: 0.305.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -28,16 +28,16 @@ dependencies:
28
28
  name: minitest
29
29
  requirement: !ruby/object:Gem::Requirement
30
30
  requirements:
31
- - - '='
31
+ - - "~>"
32
32
  - !ruby/object:Gem::Version
33
- version: 5.27.0
33
+ version: '6.0'
34
34
  type: :development
35
35
  prerelease: false
36
36
  version_requirements: !ruby/object:Gem::Requirement
37
37
  requirements:
38
- - - '='
38
+ - - "~>"
39
39
  - !ruby/object:Gem::Version
40
- version: 5.27.0
40
+ version: '6.0'
41
41
  - !ruby/object:Gem::Dependency
42
42
  name: rake
43
43
  requirement: !ruby/object:Gem::Requirement
@@ -62,12 +62,6 @@ files:
62
62
  - LICENSE.txt
63
63
  - README.md
64
64
  - lib/state_machines.rb
65
- - lib/state_machines/async_mode.rb
66
- - lib/state_machines/async_mode/async_event_extensions.rb
67
- - lib/state_machines/async_mode/async_events.rb
68
- - lib/state_machines/async_mode/async_machine.rb
69
- - lib/state_machines/async_mode/async_transition_collection.rb
70
- - lib/state_machines/async_mode/thread_safe_state.rb
71
65
  - lib/state_machines/branch.rb
72
66
  - lib/state_machines/callback.rb
73
67
  - lib/state_machines/core.rb
@@ -83,7 +77,6 @@ files:
83
77
  - lib/state_machines/integrations/base.rb
84
78
  - lib/state_machines/machine.rb
85
79
  - lib/state_machines/machine/action_hooks.rb
86
- - lib/state_machines/machine/async_extensions.rb
87
80
  - lib/state_machines/machine/callbacks.rb
88
81
  - lib/state_machines/machine/class_methods.rb
89
82
  - lib/state_machines/machine/configuration.rb
@@ -95,7 +88,6 @@ files:
95
88
  - lib/state_machines/machine/scoping.rb
96
89
  - lib/state_machines/machine/state_methods.rb
97
90
  - lib/state_machines/machine/utilities.rb
98
- - lib/state_machines/machine/validation.rb
99
91
  - lib/state_machines/machine_collection.rb
100
92
  - lib/state_machines/macro_methods.rb
101
93
  - lib/state_machines/matcher.rb
@@ -111,6 +103,7 @@ files:
111
103
  - lib/state_machines/syntax_validator.rb
112
104
  - lib/state_machines/test_helper.rb
113
105
  - lib/state_machines/transition.rb
106
+ - lib/state_machines/transition_claim.rb
114
107
  - lib/state_machines/transition_collection.rb
115
108
  - lib/state_machines/version.rb
116
109
  homepage: https://github.com/state-machines/state_machines
@@ -128,14 +121,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
128
121
  requirements:
129
122
  - - ">="
130
123
  - !ruby/object:Gem::Version
131
- version: 3.2.0
124
+ version: '4.0'
132
125
  required_rubygems_version: !ruby/object:Gem::Requirement
133
126
  requirements:
134
127
  - - ">="
135
128
  - !ruby/object:Gem::Version
136
129
  version: '0'
137
130
  requirements: []
138
- rubygems_version: 4.0.10
131
+ rubygems_version: 4.0.20
139
132
  specification_version: 4
140
133
  summary: State machines for attributes
141
134
  test_files: []
@@ -1,49 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Extensions to Event class for async bang methods
6
- module AsyncEventExtensions
7
- # Generate async bang methods for events when async mode is enabled
8
- def define_helper(scope, method, *args, &block)
9
- result = super
10
-
11
- # If this is an async-enabled machine and we're defining an event method
12
- if scope == :instance && method !~ /_async[!]?$/ && machine.async_mode_enabled?
13
- qualified_name = method.to_s
14
-
15
- # Create async version that returns a task
16
- machine.define_helper(scope, "#{qualified_name}_async") do |machine, object, *method_args, **kwargs|
17
- # Find the machine that has this event
18
- target_machine = object.class.state_machines.values.find { |m| m.events[name] }
19
-
20
- unless defined?(::Async::Task) && ::Async::Task.current?
21
- raise RuntimeError, "#{qualified_name}_async must be called within an Async context"
22
- end
23
-
24
- Async do
25
- target_machine.events[name].fire(object, *method_args, **kwargs)
26
- end
27
- end
28
-
29
- # Create async bang version that raises exceptions when awaited
30
- machine.define_helper(scope, "#{qualified_name}_async!") do |machine, object, *method_args, **kwargs|
31
- # Find the machine that has this event
32
- target_machine = object.class.state_machines.values.find { |m| m.events[name] }
33
-
34
- unless defined?(::Async::Task) && ::Async::Task.current?
35
- raise RuntimeError, "#{qualified_name}_async! must be called within an Async context"
36
- end
37
-
38
- Async do
39
- # Use fire method which will raise exceptions on invalid transitions
40
- target_machine.events[name].fire(object, *method_args, **kwargs) || raise(StateMachines::InvalidTransition.new(object, target_machine, name))
41
- end
42
- end
43
- end
44
-
45
- result
46
- end
47
- end
48
- end
49
- end
@@ -1,286 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Async-aware event firing capabilities using the async gem
6
- module AsyncEvents
7
- # Fires an event asynchronously using Async
8
- # Returns an Async::Task that can be awaited for the result
9
- #
10
- # Example:
11
- # Async do
12
- # task = vehicle.async_fire_event(:ignite)
13
- # result = task.wait # => true/false
14
- # end
15
- def async_fire_event(event_name, *args)
16
- # Find the machine that has this event
17
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
18
-
19
- unless machine
20
- raise ArgumentError, "Event #{event_name} not found in any state machine"
21
- end
22
-
23
- # Must be called within an Async context
24
- unless defined?(::Async::Task) && ::Async::Task.current?
25
- raise RuntimeError, "async_fire_event must be called within an Async context. Use: Async { vehicle.async_fire_event(:event) }"
26
- end
27
-
28
- Async do
29
- machine.events[event_name].fire(self, *args)
30
- end
31
- end
32
-
33
- # Fires multiple events asynchronously across different state machines
34
- # Returns an array of Async::Tasks for concurrent execution
35
- #
36
- # Example:
37
- # Async do
38
- # tasks = vehicle.async_fire_events(:ignite, :buy_insurance)
39
- # results = tasks.map(&:wait) # => [true, true]
40
- # end
41
- def async_fire_events(*event_names)
42
- event_names.map { |event_name| async_fire_event(event_name) }
43
- end
44
-
45
- # Fires an event asynchronously and waits for completion
46
- # This is a convenience method that creates and waits for the task
47
- #
48
- # Example:
49
- # result = vehicle.fire_event_async(:ignite) # => true/false
50
- def fire_event_async(event_name, *args)
51
- raise NoMethodError, "undefined method `fire_event_async' for #{self}" unless has_async_machines?
52
- # Find the machine that has this event
53
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
54
-
55
- unless machine
56
- raise ArgumentError, "Event #{event_name} not found in any state machine"
57
- end
58
-
59
- if defined?(::Async::Task) && ::Async::Task.current?
60
- # Already in async context, just fire directly
61
- machine.events[event_name].fire(self, *args)
62
- else
63
- # Create async context and wait for result
64
- Async do
65
- machine.events[event_name].fire(self, *args)
66
- end.wait
67
- end
68
- end
69
-
70
- # Fires multiple events asynchronously and waits for all completions
71
- # Returns results in the same order as the input events
72
- #
73
- # Example:
74
- # results = vehicle.fire_events_async(:ignite, :buy_insurance) # => [true, true]
75
- def fire_events_async(*event_names)
76
- raise NoMethodError, "undefined method `fire_events_async' for #{self}" unless has_async_machines?
77
- if defined?(::Async::Task) && ::Async::Task.current?
78
- # Already in async context, run concurrently
79
- tasks = event_names.map { |event_name| async_fire_event(event_name) }
80
- tasks.map(&:wait)
81
- else
82
- # Create async context and run concurrently
83
- Async do
84
- tasks = event_names.map { |event_name| async_fire_event(event_name) }
85
- tasks.map(&:wait)
86
- end.wait
87
- end
88
- end
89
-
90
- # Fires an event asynchronously using Async and raises exception on failure
91
- # Returns an Async::Task that raises StateMachines::InvalidTransition when awaited
92
- #
93
- # Example:
94
- # Async do
95
- # begin
96
- # task = vehicle.async_fire_event!(:ignite)
97
- # result = task.wait
98
- # puts "Event fired successfully!"
99
- # rescue StateMachines::InvalidTransition => e
100
- # puts "Transition failed: #{e.message}"
101
- # end
102
- # end
103
- def async_fire_event!(event_name, *args)
104
- # Find the machine that has this event
105
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
106
-
107
- unless machine
108
- raise ArgumentError, "Event #{event_name} not found in any state machine"
109
- end
110
-
111
- # Must be called within an Async context
112
- unless defined?(::Async::Task) && ::Async::Task.current?
113
- raise RuntimeError, "async_fire_event! must be called within an Async context. Use: Async { vehicle.async_fire_event!(:event) }"
114
- end
115
-
116
- Async do
117
- fire_with_bang(machine, event_name, *args)
118
- end
119
- end
120
-
121
- # Fires an event asynchronously and waits for result, raising exceptions on failure
122
- # This is a convenience method that creates and waits for the task
123
- #
124
- # Example:
125
- # begin
126
- # result = vehicle.fire_event_async!(:ignite)
127
- # puts "Event fired successfully!"
128
- # rescue StateMachines::InvalidTransition => e
129
- # puts "Transition failed: #{e.message}"
130
- # end
131
- def fire_event_async!(event_name, *args)
132
- raise NoMethodError, "undefined method `fire_event_async!' for #{self}" unless has_async_machines?
133
- # Find the machine that has this event
134
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
135
-
136
- unless machine
137
- raise ArgumentError, "Event #{event_name} not found in any state machine"
138
- end
139
-
140
- if defined?(::Async::Task) && ::Async::Task.current?
141
- # Already in async context, just fire directly with bang behavior
142
- fire_with_bang(machine, event_name, *args)
143
- else
144
- # Create async context and wait for result (may raise exception)
145
- Async do
146
- fire_with_bang(machine, event_name, *args)
147
- end.wait
148
- end
149
- end
150
-
151
- # Dynamically handle individual event async methods
152
- # This provides launch_async, launch_async!, arm_weapons_async, etc.
153
- def method_missing(method_name, *args, **kwargs, &block)
154
- method_str = method_name.to_s
155
-
156
- # Check if this is an async event method
157
- if method_str.end_with?('_async!')
158
- # Remove the _async! suffix to get the base event method
159
- base_method = method_str.chomp('_async!').to_sym
160
-
161
- # Check if the base method exists and this machine is async-enabled
162
- if respond_to?(base_method) && async_method_for_event?(base_method)
163
- return handle_individual_event_async_bang(base_method, *args, **kwargs)
164
- end
165
- elsif method_str.end_with?('_async')
166
- # Remove the _async suffix to get the base event method
167
- base_method = method_str.chomp('_async').to_sym
168
-
169
- # Check if the base method exists and this machine is async-enabled
170
- if respond_to?(base_method) && async_method_for_event?(base_method)
171
- return handle_individual_event_async(base_method, *args, **kwargs)
172
- end
173
- end
174
-
175
- # If not an async method, call the original method_missing
176
- super
177
- end
178
-
179
- # Check if we should respond to async methods for this event
180
- def respond_to_missing?(method_name, include_private = false)
181
- # Only provide async methods if this object has async-enabled machines
182
- return super unless has_async_machines?
183
-
184
- method_str = method_name.to_s
185
-
186
- if method_str.end_with?('_async!') || method_str.end_with?('_async')
187
- base_method = method_str.chomp('_async!').chomp('_async').to_sym
188
- return respond_to?(base_method) && async_method_for_event?(base_method)
189
- end
190
-
191
- super
192
- end
193
-
194
- # Check if this object has any async-enabled state machines
195
- def has_async_machines?
196
- self.class.state_machines.any? { |name, machine| machine.async_mode_enabled? }
197
- end
198
-
199
- private
200
-
201
- # Fires the event on the given machine, raising InvalidTransition on failure
202
- def fire_with_bang(machine, event_name, *)
203
- machine.events[event_name].fire(self, *) || raise(StateMachines::InvalidTransition.new(self, machine, event_name))
204
- end
205
-
206
- # Check if this event method should have async versions
207
- def async_method_for_event?(event_method)
208
- # Find which machine contains this event
209
- self.class.state_machines.each do |name, machine|
210
- if machine.async_mode_enabled?
211
- # Check if this event method belongs to this machine
212
- machine.events.each do |event|
213
- qualified_name = event.qualified_name
214
- if qualified_name.to_sym == event_method || "#{qualified_name}!".to_sym == event_method
215
- return true
216
- end
217
- end
218
- end
219
- end
220
- false
221
- end
222
-
223
- # Handle individual event async methods (returns task)
224
- def handle_individual_event_async(event_method, *args, **kwargs)
225
-
226
- unless defined?(::Async::Task) && ::Async::Task.current?
227
- raise RuntimeError, "#{event_method}_async must be called within an Async context"
228
- end
229
-
230
- Async do
231
- send(event_method, *args, **kwargs)
232
- end
233
- end
234
-
235
- # Handle individual event async bang methods (returns task, raises on failure)
236
- def handle_individual_event_async_bang(event_method, *args, **kwargs)
237
- # Extract event name from method and use bang version
238
- bang_method = "#{event_method}!".to_sym
239
-
240
- unless defined?(::Async::Task) && ::Async::Task.current?
241
- raise RuntimeError, "#{event_method}_async! must be called within an Async context"
242
- end
243
-
244
- Async do
245
- send(bang_method, *args, **kwargs)
246
- end
247
- end
248
-
249
- # Extract event name from method name, handling namespaced events
250
- def extract_event_name(method_name)
251
- method_str = method_name.to_s
252
-
253
- # Find the machine and event for this method
254
- self.class.state_machines.each do |name, machine|
255
- machine.events.each do |event|
256
- qualified_name = event.qualified_name
257
- if qualified_name.to_s == method_str || "#{qualified_name}!".to_s == method_str
258
- return event.name
259
- end
260
- end
261
- end
262
-
263
- # Fallback: assume the method name is the event name
264
- method_str.chomp('!').to_sym
265
- end
266
-
267
- public
268
-
269
- # Fires multiple events concurrently within an async context
270
- # This method should be called from within an Async block
271
- #
272
- # Example:
273
- # Async do
274
- # results = vehicle.fire_events_concurrent(:ignite, :buy_insurance)
275
- # end
276
- def fire_events_concurrent(*event_names)
277
- unless defined?(::Async::Task) && ::Async::Task.current?
278
- raise RuntimeError, "fire_events_concurrent must be called within an Async context"
279
- end
280
-
281
- tasks = async_fire_events(*event_names)
282
- tasks.map(&:wait)
283
- end
284
- end
285
- end
286
- end