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
@@ -19,6 +19,7 @@ require 'state_machines/matcher'
19
19
  require 'state_machines/matcher_helpers'
20
20
 
21
21
  require 'state_machines/transition'
22
+ require 'state_machines/transition_claim'
22
23
  require 'state_machines/transition_collection'
23
24
 
24
25
  require 'state_machines/branch'
@@ -64,11 +64,19 @@ module StateMachines
64
64
  # The current state value for the machine
65
65
  attr_reader :from
66
66
 
67
+ # Why the transition was refused: the reason recorded for the event on the
68
+ # object when the error was built.
69
+ #
70
+ # @return [:no_transition, :guard, :halted, :action_failed, :contended, nil]
71
+ # @see StateMachines::Event#refusal
72
+ attr_reader :reason
73
+
67
74
  def initialize(object, machine, event) # :nodoc:
68
75
  @machine = machine
69
76
  @from_state = machine.states.match!(object)
70
77
  @from = machine.read(object, :state)
71
78
  @event = machine.events.fetch(event)
79
+ @reason = @event.refusal(object)
72
80
  errors = machine.errors_for(object)
73
81
 
74
82
  message = "Cannot transition #{machine.name} via :#{self.event} from #{from_name.inspect}"
@@ -102,14 +110,54 @@ module StateMachines
102
110
  # The set of events that failed the transition(s)
103
111
  attr_reader :events
104
112
 
113
+ # The refusal reason of each event that caused the failure, keyed by the
114
+ # event name as given. Events refused only because another one was are
115
+ # left out.
116
+ #
117
+ # @return [Hash{Symbol => Symbol}]
118
+ # @see StateMachines::Event#refusal
119
+ attr_reader :reasons
120
+
105
121
  def initialize(object, events) # :nodoc:
106
122
  @events = events
123
+ @reasons = refusal_reasons(object, events)
107
124
 
108
125
  super(object, "Cannot run events in parallel: #{events * ', '}")
109
126
  end
127
+
128
+ private
129
+
130
+ # Reads the recorded refusal reason of each given event on the object,
131
+ # finding each event across the object's machines by its qualified name.
132
+ #
133
+ # @param object [Object] the object the events were fired on
134
+ # @param events [Array<Symbol>] the qualified event names that were fired
135
+ # @return [Hash{Symbol => Symbol}] the reason per event name, leaving out
136
+ # events without one (and every event when the object has no machines)
137
+ def refusal_reasons(object, events)
138
+ return {} unless object.class.respond_to?(:state_machines)
139
+
140
+ machines = object.class.state_machines.values
141
+ events.each_with_object({}) do |event_name, reasons|
142
+ event = machines.lazy.filter_map { |machine| machine.events[event_name, :qualified_name] }.first
143
+ reason = event&.refusal(object)
144
+ reasons[event_name] = reason if reason
145
+ end
146
+ end
110
147
  end
111
148
 
112
- # A method was called in an invalid state context
113
- class InvalidContext < Error
149
+ # A state-specific method was called on an object whose current state does
150
+ # not define it. It is a NoMethodError, as documented for state behaviors:
151
+ # the method does not exist for the object in that state. #object is the
152
+ # receiver, as on the other StateMachines errors.
153
+ class InvalidContext < NoMethodError
154
+ def initialize(object, message = nil, name = nil, args = []) # :nodoc:
155
+ super(message, name, args, receiver: object)
156
+ end
157
+
158
+ # The object the method was called on
159
+ def object
160
+ receiver
161
+ end
114
162
  end
115
163
  end
@@ -192,26 +192,37 @@ module StateMachines
192
192
  end
193
193
  end
194
194
 
195
- private
195
+ # Patterns refused in String conditions before they are evaluated
196
+ DANGEROUS_PATTERNS = [
197
+ /`.*`/, # Backticks (shell execution)
198
+ /system\s*\(/, # System calls
199
+ /exec\s*\(/, # Exec calls
200
+ /eval\s*\(/, # Nested eval
201
+ /require\s+['"]/, # Require statements
202
+ /load\s+['"]/, # Load statements
203
+ /File\./, # File operations
204
+ /IO\./, # IO operations
205
+ /Dir\./, # Directory operations
206
+ /Kernel\./ # Kernel operations
207
+ ].freeze
208
+ private_constant :DANGEROUS_PATTERNS
196
209
 
197
- # Validates string input before eval to prevent code injection
198
- # This is a basic safety check - not foolproof security
210
+ # Checks a String condition or callback exactly as core does before
211
+ # evaluating it. This is a basic safety check, not a sandbox.
212
+ #
213
+ # StateMachines::EvalHelpers.validate_eval_string('vehicle.seatbelt_on?') # => nil
214
+ # StateMachines::EvalHelpers.validate_eval_string('`ls`') # => SecurityError
215
+ # StateMachines::EvalHelpers.validate_eval_string('if true') # => ArgumentError
216
+ #
217
+ # Raises SecurityError for a pattern it refuses (shell, eval, require,
218
+ # File / IO / Dir / Kernel access) and ArgumentError for invalid syntax.
219
+ # +yield+ is allowed, as a String evaluated with a block may yield.
220
+ # Returns nil when the string may be evaluated.
221
+ #
222
+ # A module function: public on the module, and private in the classes
223
+ # that include EvalHelpers, where evaluation calls it.
199
224
  def validate_eval_string(method_string)
200
- # Check for obviously dangerous patterns
201
- dangerous_patterns = [
202
- /`.*`/, # Backticks (shell execution)
203
- /system\s*\(/, # System calls
204
- /exec\s*\(/, # Exec calls
205
- /eval\s*\(/, # Nested eval
206
- /require\s+['"]/, # Require statements
207
- /load\s+['"]/, # Load statements
208
- /File\./, # File operations
209
- /IO\./, # IO operations
210
- /Dir\./, # Directory operations
211
- /Kernel\./ # Kernel operations
212
- ]
213
-
214
- dangerous_patterns.each do |pattern|
225
+ DANGEROUS_PATTERNS.each do |pattern|
215
226
  raise SecurityError, "Potentially dangerous code detected in eval string: #{method_string.inspect}" if method_string.match?(pattern)
216
227
  end
217
228
 
@@ -222,6 +233,8 @@ module StateMachines
222
233
  rescue SyntaxError => e
223
234
  raise ArgumentError, "Invalid Ruby syntax in eval string: #{e.message}"
224
235
  end
236
+ nil
225
237
  end
238
+ module_function :validate_eval_string
226
239
  end
227
240
  end
@@ -9,6 +9,28 @@ module StateMachines
9
9
  class Event
10
10
  include MatcherHelpers
11
11
 
12
+ # The object instance variable holding the most recent refusal reason per
13
+ # machine and event
14
+ REFUSALS_VARIABLE = :@_state_machine_refusals
15
+
16
+ # Serialises the creation and updates of an object's refusal reasons, so
17
+ # that concurrent attempts on one object do not lose each other's reason
18
+ REFUSALS_LOCK = Thread::Mutex.new
19
+
20
+ class << self
21
+ # Forgets every refusal reason recorded on the given object, e.g. when
22
+ # it is copied or reloaded.
23
+ #
24
+ # @api private
25
+ # @param object [Object] the object whose reasons are forgotten
26
+ # @return [void]
27
+ def clear_refusals(object)
28
+ return if object.frozen? || !object.instance_variable_defined?(REFUSALS_VARIABLE)
29
+
30
+ object.remove_instance_variable(REFUSALS_VARIABLE)
31
+ end
32
+ end
33
+
12
34
  # The state machine for which this event is defined
13
35
  attr_accessor :machine
14
36
 
@@ -99,14 +121,45 @@ module StateMachines
99
121
  #
100
122
  # See StateMachines::Machine#transition for a description of the possible
101
123
  # configurations for defining transitions.
124
+ #
125
+ # Branch callbacks:
126
+ # * <tt>:before</tt>, <tt>:around</tt>, <tt>:after</tt> - Callbacks that
127
+ # run only when this branch is the one selected, so its guards apply.
128
+ # Each takes what after_transition's +:do+ takes: a method name, an
129
+ # Array of them, or a Proc / Method. They run closest to the state
130
+ # change: after the machine's before / around callbacks, in the order
131
+ # written, and (+:after+, on success only) before the machine's after
132
+ # callbacks. See StateMachines::Branch#callbacks.
133
+ #
134
+ # transition :parked => :idling, :after => :log_ignition
135
+ #
136
+ # These keys, and +:do+ (refused: use +:after+), are reserved: a state
137
+ # named :after is written <tt>transition from: :after, to: :parked</tt>.
102
138
  def transition(options)
103
139
  raise ArgumentError, 'Must specify as least one transition requirement' if options.empty?
140
+ raise ArgumentError, 'transition does not take do:; use after: (or before:/around:)' if options.key?(:do)
141
+
142
+ # before: / after: / around: are this branch's callbacks, in the order
143
+ # given; the keys are reserved, so they are never read as a state
144
+ # select, not slice: the order the callbacks were written is their order
145
+ given = options.select { |key, _| BRANCH_CALLBACK_TYPES.include?(key) } # rubocop:disable Style/HashSlice
146
+ options = options.except(*BRANCH_CALLBACK_TYPES)
147
+ # Callback keys are always callbacks. Without any state requirement left
148
+ # (only guards and/or callbacks), the transition reads as the old
149
+ # `transition after: :x` (from a state named :after), so refuse it rather
150
+ # than silently turning it into an all => all branch
151
+ raise reserved_key_error(*given.first) if given.any? && (options.keys - NON_STATE_KEYS).empty?
152
+
153
+ callbacks = given.map do |type, callables|
154
+ assert_branch_callback!(type, callables)
155
+ machine.branch_callback(type, callables)
156
+ end
104
157
 
105
158
  # Only a certain subset of explicit options are allowed for transition
106
159
  # requirements
107
160
  StateMachines::OptionsValidator.assert_valid_keys!(options, :from, :to, :except_from, :except_to, :if, :unless, :if_state, :unless_state, :if_all_states, :unless_all_states, :if_any_state, :unless_any_state) if (options.keys - %i[from to on except_from except_to except_on if unless if_state unless_state if_all_states unless_all_states if_any_state unless_any_state]).empty?
108
161
 
109
- branches << branch = Branch.new(options.merge(on: name))
162
+ branches << branch = Branch.new(Branch.options_with_callbacks(options.merge(on: name), callbacks))
110
163
  @known_states |= branch.known_states
111
164
  branch
112
165
  end
@@ -152,7 +205,7 @@ module StateMachines
152
205
  match[:to].filter(values).first
153
206
  end
154
207
 
155
- return Transition.new(object, machine, name, from, to, !custom_from_state)
208
+ return Transition.new(object, machine, name, from, to, !custom_from_state, branch: branch)
156
209
  end
157
210
 
158
211
  # No transition matched
@@ -161,21 +214,118 @@ module StateMachines
161
214
 
162
215
  # Attempts to perform the next available transition on the given object.
163
216
  # If no transitions can be made, then this will return false, otherwise
164
- # true.
217
+ # the performed {StateMachines::Transition}.
165
218
  #
166
219
  # Any additional arguments are passed to the StateMachines::Transition#perform
167
220
  # instance method.
221
+ #
222
+ # The reason for a refusal is recorded on the object and can be read back
223
+ # with {#refusal} (or the generated `*_refusal` helper).
224
+ #
225
+ # @return [StateMachines::Transition, false] the performed transition, or
226
+ # false if the event was refused
227
+ # @see #refusal
168
228
  def fire(object, *event_args)
169
229
  machine.reset(object)
170
230
 
171
- if (transition = transition_for(object, {}, *event_args))
231
+ transition = begin
232
+ transition_for(object, {}, *event_args)
233
+ rescue StandardError
234
+ # A guard raised before this attempt had an outcome
235
+ record_refusal(object, nil)
236
+ raise
237
+ end
238
+
239
+ if transition
172
240
  transition.perform(*event_args)
173
241
  else
242
+ record_refusal(object, refusal_without_transition(object))
174
243
  on_failure(object, *event_args)
175
244
  false
176
245
  end
177
246
  end
178
247
 
248
+ # The reason the most recent attempt to fire this event on the given object
249
+ # was refused.
250
+ #
251
+ # The reasons are:
252
+ # - :no_transition - no transition is defined for the event from the
253
+ # object's current state
254
+ # - :guard - a transition is defined from the current state, but its :if /
255
+ # :unless / state guards rejected it
256
+ # - :halted - a before_transition or around_transition callback halted the
257
+ # transition
258
+ # - :action_failed - the machine's action (e.g. save) did not succeed
259
+ # - :contended - a concurrent transition held or moved the attribute
260
+ # first; only on machines that claim their transitions (see
261
+ # {StateMachines::Machine#claims_transitions?}), such as async mode
262
+ # machines of state_machines-async
263
+ #
264
+ # When the event was fired in parallel with others (see
265
+ # {StateMachines::InstanceMethods#fire_events}), only the events that caused
266
+ # the refusal carry a reason; the others read nil. When the action failed
267
+ # because an event attribute it performed was refused (see
268
+ # {StateMachines::TransitionCollection#perform}), the event carries that
269
+ # inner reason.
270
+ #
271
+ # The reason describes the most recent attempt *on the object*, whichever
272
+ # caller made it: it is not tied to a caller. When several threads or
273
+ # fibers fire events on the same object concurrently, each should rely on
274
+ # its own result - the bang method's {StateMachines::InvalidTransition#reason}
275
+ # (or {StateMachines::Transition#refusal} of a transition it performed) -
276
+ # rather than on this reader, which another caller may have overwritten.
277
+ #
278
+ # A frozen object records no reason, so this reads nil for it. A copy
279
+ # (+dup+ / +clone+) starts with no reasons, as it has made no attempt.
280
+ #
281
+ # @param object [Object] the object the event was fired on
282
+ # @return [:no_transition, :guard, :halted, :action_failed, :contended, nil]
283
+ # the refusal reason, or nil if the most recent attempt succeeded, raised
284
+ # before an outcome, or none was made
285
+ # @example
286
+ # vehicle.state # => "idling"
287
+ # vehicle.ignite # => false
288
+ # vehicle.class.state_machine.events[:ignite].refusal(vehicle) # => :no_transition
289
+ # vehicle.ignite_refusal # => :no_transition
290
+ def refusal(object)
291
+ return if object.frozen?
292
+
293
+ refusals = object.instance_variable_get(REFUSALS_VARIABLE)
294
+ refusals && refusals[[machine.name, name]]
295
+ end
296
+
297
+ # Records the reason the event was refused on the given object, or clears
298
+ # it when reason is nil. Nothing is recorded on a frozen object.
299
+ #
300
+ # @param object [Object] the object the event was fired on
301
+ # @param reason [Symbol, nil] the refusal reason (see {#refusal}), or nil
302
+ # to clear it
303
+ # @return [void]
304
+ def record_refusal(object, reason) # :nodoc:
305
+ return if object.frozen?
306
+
307
+ key = [machine.name, name]
308
+ REFUSALS_LOCK.synchronize do
309
+ refusals = object.instance_variable_get(REFUSALS_VARIABLE)
310
+ if reason
311
+ (refusals || object.instance_variable_set(REFUSALS_VARIABLE, {}))[key] = reason
312
+ else
313
+ refusals&.delete(key)
314
+ end
315
+ end
316
+ end
317
+
318
+ # Why no transition could be built for the object. The conditions are not
319
+ # evaluated again.
320
+ #
321
+ # @param object [Object] the object the event was fired on
322
+ # @return [:guard, :no_transition] :guard when a branch matches the current
323
+ # state but its conditions rejected it, otherwise :no_transition
324
+ def refusal_without_transition(object) # :nodoc:
325
+ query = { from: machine.states.match!(object).name, guard: false }
326
+ branches.any? { |branch| branch.matches?(object, query) } ? :guard : :no_transition
327
+ end
328
+
179
329
  # Marks the object as invalid and runs any failure callbacks associated with
180
330
  # this event. This should get called anytime this event fails to transition.
181
331
  def on_failure(object, *args)
@@ -238,10 +388,43 @@ module StateMachines
238
388
  machine.event(name).fire(object, *args, **kwargs)
239
389
  end
240
390
 
391
+ # Gets the reason the most recent attempt to fire the event was refused,
392
+ # or nil if it succeeded
393
+ machine.define_helper(:instance, "#{qualified_name}_refusal") do |machine, object|
394
+ machine.event(name).refusal(object)
395
+ end
396
+
241
397
  # Fires the event, raising an exception if it fails
242
398
  machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args, **kwargs|
243
399
  object.send(qualified_name, *args, **kwargs) || raise(StateMachines::InvalidTransition.new(object, machine, name))
244
400
  end
245
401
  end
402
+ # The keys of a transition's options that hold branch callbacks
403
+ BRANCH_CALLBACK_TYPES = %i[before around after].freeze
404
+ private_constant :BRANCH_CALLBACK_TYPES
405
+
406
+ # Transition options that are not state requirements (the event and guards)
407
+ NON_STATE_KEYS = %i[on except_on if unless if_state unless_state if_all_states unless_all_states if_any_state unless_any_state].freeze
408
+ private_constant :NON_STATE_KEYS
409
+
410
+ private
411
+
412
+ # Checks a branch callback's value by type only, so the outcome never
413
+ # depends on which states exist or were declared first
414
+ def assert_branch_callback!(type, callables)
415
+ values = callables.is_a?(Array) ? callables : [callables]
416
+ raise ArgumentError, "#{type}: needs at least one method name, Proc or Method" if values.empty?
417
+
418
+ invalid = values.reject { |value| value.is_a?(Symbol) || value.is_a?(String) || value.is_a?(Proc) || value.is_a?(Method) }
419
+ return if invalid.empty?
420
+
421
+ raise ArgumentError, "#{type}: takes method names (Symbol/String), Procs or Methods, not #{invalid.first.inspect}"
422
+ end
423
+
424
+ def reserved_key_error(type, value)
425
+ to = value.is_a?(Matcher) ? value.description : value.inspect
426
+ ArgumentError.new("#{type}: is reserved in transition for a branch callback; " \
427
+ "to transition from a state named #{type.inspect}, write `transition from: #{type.inspect}, to: #{to}`")
428
+ end
246
429
  end
247
430
  end
@@ -129,7 +129,12 @@ module StateMachines
129
129
  if event = self[event_name.to_sym, :name]
130
130
  event.transition_for(object) || begin
131
131
  # No valid transition: invalidate
132
- machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]]) if invalidate
132
+ if invalidate
133
+ reason = event.refusal_without_transition(object)
134
+ event.record_refusal(object, reason)
135
+ TransitionCollection.report_nested_refusal(object, reason)
136
+ machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]])
137
+ end
133
138
  false
134
139
  end
135
140
  else
@@ -22,6 +22,10 @@ module StateMachines
22
22
  end
23
23
 
24
24
  module InstanceMethods
25
+ # Per-object concurrency state, created on demand: the transition claims.
26
+ # Never copied (see #initialize_copy).
27
+ TRANSIENT_VARIABLES = %i[@_state_machine_transition_claims].freeze
28
+
25
29
  # Runs one or more events in parallel. All events will run through the
26
30
  # following steps:
27
31
  # * Before callbacks
@@ -141,6 +145,24 @@ module StateMachines
141
145
  fire_events(*(events + [run_action])) || raise(StateMachines::InvalidParallelTransition.new(self, events))
142
146
  end
143
147
 
148
+ # A copy (+dup+ / +clone+) has made no attempt to fire an event, so it
149
+ # starts with no refusal reasons instead of sharing the original's. It
150
+ # also gets its own transition claims (created on demand) instead of
151
+ # sharing the original's.
152
+ #
153
+ # A class defining its own +initialize_copy+ must call +super+.
154
+ #
155
+ # @param orig [Object] the object being copied
156
+ # @return [void]
157
+ # @see StateMachines::Event#refusal
158
+ def initialize_copy(orig)
159
+ super
160
+ StateMachines::Event.clear_refusals(self)
161
+ TRANSIENT_VARIABLES.each do |ivar|
162
+ remove_instance_variable(ivar) if instance_variable_defined?(ivar)
163
+ end
164
+ end
165
+
144
166
  protected
145
167
 
146
168
  def initialize_state_machines(options = {}, &) # :nodoc:
@@ -5,6 +5,7 @@ module StateMachines
5
5
  # state machine
6
6
  class HelperModule < Module # :nodoc:
7
7
  def initialize(machine, kind)
8
+ super()
8
9
  @machine = machine
9
10
  @kind = kind
10
11
  end
@@ -27,16 +27,19 @@ module StateMachines
27
27
  def define_action_hook
28
28
  action_hook = self.action_hook
29
29
  action = self.action
30
- private_action_hook = owner_class.private_method_defined?(action_hook)
31
-
32
- # Only define helper if it hasn't
33
- define_helper :instance, <<-END_EVAL, __FILE__, __LINE__ + 1
34
- def #{action_hook}(*)
35
- self.class.state_machines.transitions(self, #{action.inspect}).perform { super }
36
- end
37
-
38
- private #{action_hook.inspect} if #{private_action_hook}
39
- END_EVAL
30
+ # The hook replaces the action, so it keeps its exact visibility
31
+ visibility = if owner_class.private_method_defined?(action_hook) then :private
32
+ elsif owner_class.protected_method_defined?(action_hook) then :protected
33
+ end
34
+
35
+ # define_method, not a def in evaluated source: the action is a method
36
+ # the owner already has, and Ruby allows names (:"save it") that no def
37
+ # can spell
38
+ helper = @helper_modules[:instance]
39
+ helper.send(:define_method, action_hook) do |*args, **kwargs, &block|
40
+ self.class.state_machines.transitions(self, action).perform { super(*args, **kwargs, &block) }
41
+ end
42
+ helper.send(visibility, action_hook) if visibility
40
43
  end
41
44
 
42
45
  # The method to hook into for triggering transitions when invoked. By
@@ -316,8 +316,23 @@ module StateMachines
316
316
  add_callback(:failure, parsed_options, &)
317
317
  end
318
318
 
319
+ # Builds the Callback for a branch's before: / after: / around: (see
320
+ # Event#transition), configured like the machine's own callbacks
321
+ def branch_callback(type, callables) # :nodoc:
322
+ options = { do: callables }
323
+ terminator = callback_terminator
324
+ options[:terminator] = terminator if terminator
325
+ Callback.new(type, options)
326
+ end
327
+
319
328
  private
320
329
 
330
+ # The terminator for this machine's callbacks; integrations override it
331
+ # (nil keeps Callback's default)
332
+ def callback_terminator
333
+ nil
334
+ end
335
+
321
336
  def add_transition_callback(type, args, options, &)
322
337
  # Extract legacy positional arguments and merge with keyword options
323
338
  parsed_options = parse_callback_arguments(args, options)
@@ -3,6 +3,11 @@
3
3
  module StateMachines
4
4
  class Machine
5
5
  module ClassMethods
6
+ # Machine options that an extension gem provides, mapped to that gem.
7
+ # A loaded extension consumes its option before the core validates the
8
+ # options, so the core meeting one means the gem is not loaded.
9
+ EXTENSION_OPTIONS = { async: 'state_machines-async' }.freeze
10
+
6
11
  # Attempts to find or create a state machine for the given class. For
7
12
  # example,
8
13
  #
@@ -14,6 +19,10 @@ module StateMachines
14
19
  # If a machine of the given name already exists in one of the class's
15
20
  # superclasses, then a copy of that machine will be created and stored
16
21
  # in the new owner class (the original will remain unchanged).
22
+ #
23
+ # Reopening an existing machine applies the options in
24
+ # Machine#reopen_options (+:initial+, plus any a loaded extension adds);
25
+ # any other option raises ArgumentError instead of being ignored.
17
26
  def find_or_create(owner_class, *args, &)
18
27
  options = args.last.is_a?(Hash) ? args.pop : {}
19
28
  name = args.first || :state
@@ -24,15 +33,21 @@ module StateMachines
24
33
  owner_class.state_machines.values.first))) || nil
25
34
 
26
35
  if machine
36
+ reopenable = machine.reopen_options
37
+ unsupported = options.keys - reopenable
38
+ assert_extensions_loaded!(unsupported)
39
+ unless unsupported.empty?
40
+ raise ArgumentError, "Cannot change #{unsupported.map(&:inspect).join(', ')} of existing state machine " \
41
+ "#{name.inspect} on #{owner_class}; reopening it accepts only #{reopenable.map(&:inspect).join(', ')}"
42
+ end
43
+
27
44
  # Only create a new copy if changes are being made to the machine in
28
45
  # a subclass
29
46
  if machine.owner_class != owner_class && (options.any? || block_given?)
30
47
  machine = machine.clone
31
- machine.initial_state = options[:initial] if options.include?(:initial)
32
48
  machine.owner_class = owner_class
33
- # Configure async mode if requested in options
34
- machine.configure_async_mode!(options[:async]) if options.include?(:async)
35
49
  end
50
+ machine.reopen(options)
36
51
 
37
52
  # Evaluate DSL
38
53
  machine.instance_eval(&) if block_given?
@@ -48,6 +63,22 @@ module StateMachines
48
63
  raise NotImplementedError
49
64
  end
50
65
 
66
+ # Raises ArgumentError naming the gem when +keys+ holds an option of
67
+ # EXTENSION_OPTIONS, whose gem is then not loaded, so that the option is
68
+ # neither ignored nor reported as merely unknown.
69
+ #
70
+ # @api private
71
+ # @param keys [Array<Symbol>] option names the core does not accept
72
+ # @return [void]
73
+ def assert_extensions_loaded!(keys)
74
+ option = keys.find { |key| EXTENSION_OPTIONS.key?(key) }
75
+ return unless option
76
+
77
+ gem_name = EXTENSION_OPTIONS.fetch(option)
78
+ raise ArgumentError, "The #{option.inspect} state machine option is provided by the #{gem_name} gem, " \
79
+ "which is not loaded; add it to your Gemfile and require '#{gem_name}'"
80
+ end
81
+
51
82
  # Default messages to use for validation errors in ORM integrations
52
83
  # Thread-safe access via atomic operations on simple values
53
84
  attr_accessor :ignore_method_conflicts
@@ -6,22 +6,26 @@ module StateMachines
6
6
  # Initializes a new state machine with the given configuration.
7
7
  def initialize(owner_class, *args, &)
8
8
  options = args.last.is_a?(Hash) ? args.pop : {}
9
-
9
+
10
10
  # Find an integration that matches this machine's owner class
11
11
  @integration = if options.include?(:integration)
12
12
  options[:integration] && StateMachines::Integrations.find_by_name(options[:integration])
13
13
  else
14
14
  StateMachines::Integrations.match(owner_class)
15
15
  end
16
-
16
+
17
17
  # Validate options including integration-specific options
18
- valid_keys = [:attribute, :initial, :initialize, :action, :plural, :namespace, :integration, :messages, :use_transactions, :async]
18
+ valid_keys = creation_options
19
19
  valid_keys += @integration.integration_options if @integration
20
+ self.class.assert_extensions_loaded!(options.keys - valid_keys)
20
21
  StateMachines::OptionsValidator.assert_valid_keys!(options, valid_keys)
21
22
 
22
23
  if @integration
23
24
  extend @integration
25
+
24
26
  options = (@integration.defaults || {}).merge(options)
27
+ # An integration default can supply an extension's option too
28
+ self.class.assert_extensions_loaded!(options.keys - valid_keys)
25
29
  end
26
30
 
27
31
  # Add machine-wide defaults
@@ -29,6 +33,9 @@ module StateMachines
29
33
 
30
34
  # Set machine configuration
31
35
  @name = args.first || :state
36
+ # The name builds the default attribute and the @<name>_event /
37
+ # @<name>_event_transition ivars, so it must be an ivar-safe name
38
+ assert_ivar_name!(@name, 'state machine name')
32
39
  @attribute = options[:attribute] || @name
33
40
  @events = EventCollection.new(self)
34
41
  @states = StateCollection.new(self)
@@ -39,7 +46,7 @@ module StateMachines
39
46
  @use_transactions = options[:use_transactions]
40
47
  @initialize_state = options[:initialize]
41
48
  @action_hook_defined = false
42
- @async_requested = options[:async]
49
+ @integration_options = @integration ? options.slice(*@integration.integration_options).freeze : {}.freeze
43
50
 
44
51
  self.owner_class = owner_class
45
52
 
@@ -54,8 +61,7 @@ module StateMachines
54
61
  # Evaluate DSL
55
62
  instance_eval(&) if block_given?
56
63
 
57
- # Configure async mode if requested, after owner_class is set and DSL is evaluated
58
- configure_async_mode!(true) if @async_requested
64
+ after_definition(options)
59
65
 
60
66
  self.initial_state = options[:initial] unless sibling_machines.any?
61
67
  end
@@ -71,8 +77,6 @@ module StateMachines
71
77
  @states = @states.dup
72
78
  @states.machine = self
73
79
  @callbacks = { before: @callbacks[:before].dup, after: @callbacks[:after].dup, failure: @callbacks[:failure].dup }
74
- @async_requested = orig.instance_variable_get(:@async_requested)
75
- @async_mode_enabled = orig.instance_variable_get(:@async_mode_enabled)
76
80
  end
77
81
 
78
82
  # Sets the class which is the owner of this state machine. Any methods
@@ -39,10 +39,15 @@ module StateMachines
39
39
  # object or nil if no transitions can be performed. Like <tt>can_park?</tt>
40
40
  # this will also *not* run validations or callbacks. It will only
41
41
  # determine if the state machine defines a valid transition for the event.
42
+ # * <tt>park_refusal</tt> - Gets the reason the most recent attempt to fire
43
+ # the "park" event was refused (<tt>:no_transition</tt>, <tt>:guard</tt>,
44
+ # <tt>:halted</tt>, <tt>:action_failed</tt> or <tt>:contended</tt>), or nil
45
+ # if it succeeded. See {StateMachines::Event#refusal}.
42
46
  #
43
47
  # With a namespace of "car", the above names map to the following methods:
44
48
  # * <tt>can_park_car?</tt>
45
49
  # * <tt>park_car_transition</tt>
50
+ # * <tt>park_car_refusal</tt>
46
51
  # * <tt>park_car</tt>
47
52
  # * <tt>park_car!</tt>
48
53
  #