state_machines 0.301.2 → 0.303.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4f3fa05a4995ba6d3ff323c8cbf7303a061bf082237353066c01b023129d4c7f
4
- data.tar.gz: c56a60d5f74f1da251670ff4f5c782d68837a6db2f2f4c200d744adebe620b7f
3
+ metadata.gz: 9a29b27e5695470275a9549dd92e27dce0e37c3bdf00541bcfd1fc5194aa506c
4
+ data.tar.gz: 05f7e2bf30fe31ca8f616d2983a4ea2fa248a1b585f529c79ad7dd5f012c77ab
5
5
  SHA512:
6
- metadata.gz: f6ef8c77f4652d1281e4b66252e0f72395efc2143180b1e91cb437ac7934ca5d9238f3e9b56c5ab3ca7ede1e3a4123fe3ffde899b02f565601b056e7477f0884
7
- data.tar.gz: 643d203b7719acd77ec70df09bd4c46b722127bf0529e3108285ac5120ea5b0269fe195e09448664cdabcf70a86232a6496ff8f33e8e4943bc64d806b00c28d6
6
+ metadata.gz: ca1284da8da46118da332893513394e21afdadc7aa7f759327787c6e0d55d8acff3ba52e981e5cac1f2527ee3419a42d3f08443ad6c3d2b66d625c1ad246659d
7
+ data.tar.gz: c571cc39176f7d0f20e4cd75c76734a76b508678811d48faa2d34a41bc4cc72e01c063c91ee8c74861e47e3d25640df8853bdd7fe0bab4afd9481bb449035491
data/README.md CHANGED
@@ -37,7 +37,6 @@ Below is an example of many of the features offered by this plugin, including:
37
37
  * Transition callbacks
38
38
  * Conditional transitions
39
39
  * Coordinated state management guards
40
- * Asynchronous state machines (async: true)
41
40
  * State-driven instance behavior
42
41
  * Customized state values
43
42
  * Parallel events
@@ -212,7 +211,8 @@ vehicle # => #<Vehicle:0xb7cf4eac @state="first_gear", @
212
211
  vehicle.fire_state_event(:shift_up) # => #<StateMachines::Transition attribute=:state event=:shift_up ...>
213
212
 
214
213
  # Call state-driven behavior that's undefined for the state raises a NoMethodError
215
- vehicle.speed # => NoMethodError: super: no superclass method `speed' for #<Vehicle:0xb7cf4eac>
214
+ # (StateMachines::InvalidContext)
215
+ vehicle.speed # => StateMachines::InvalidContext: State :second_gear for :state is not a valid context for calling #speed
216
216
  vehicle # => #<Vehicle:0xb7cf4eac @state="second_gear", @seatbelt_on=true>
217
217
 
218
218
  # The bang (!) operator can raise exceptions if the event fails
@@ -263,7 +263,7 @@ on that object, or `nil` once an attempt succeeds:
263
263
  | `:guard` | A transition from the current state exists, but its `if:`/`unless:` (or state guards) rejected it |
264
264
  | `:halted` | A `before_transition` or `around_transition` callback halted it |
265
265
  | `:action_failed` | The machine's action (e.g. `save`) did not succeed |
266
- | `:contended` | Async mode only: a concurrent transition held or moved the attribute first |
266
+ | `:contended` | A concurrent transition held or moved the attribute first (only machines that claim their transitions, e.g. [state_machines-async](https://github.com/state-machines/state_machines-async)) |
267
267
 
268
268
  ```ruby
269
269
  vehicle = Vehicle.new # parked
@@ -447,119 +447,15 @@ StarshipBridge.new.can_red_alert?
447
447
 
448
448
  # Asynchronous State Machines
449
449
 
450
- State machines can operate asynchronously for high-performance applications. This is ideal for I/O-bound tasks, such as in web servers or other concurrent environments, where you don't want a long-running state transition (like one involving a network call) to block the entire thread.
450
+ Async mode (`state_machine ..., async: true`, `<event>_async` methods, `fire_event_async`) lives
451
+ in the [state_machines-async](https://github.com/state-machines/state_machines-async) gem. Without it
452
+ loaded, `async: true` raises `ArgumentError` naming the gem rather than being ignored.
451
453
 
452
- This feature is powered by the [async](https://github.com/socketry/async) gem and uses `concurrent-ruby` for enterprise-grade thread safety.
453
-
454
- ## Platform Compatibility
455
-
456
- **Supported Platforms:**
457
- * MRI Ruby (CRuby) 3.4+
458
- * Other Ruby engines with full Fiber scheduler support
459
-
460
- **Unsupported Platforms:**
461
- * JRuby - Falls back to synchronous mode with warnings
462
- * TruffleRuby - Falls back to synchronous mode with warnings
463
-
464
- ## Basic Async Usage
465
-
466
- Enable async mode by adding `async: true` to your state machine declaration:
467
-
468
- ```ruby
469
- class AutonomousDrone < StarfleetShip
470
- # Async-enabled state machine for autonomous operation
471
- state_machine :status, async: true, initial: :docked do
472
- event :launch do
473
- transition docked: :flying
474
- end
475
-
476
- event :land do
477
- transition flying: :docked
478
- end
479
- end
480
-
481
- # Mixed configuration: some machines async, others sync
482
- state_machine :teleporter_status, async: true, initial: :offline do
483
- event :power_up do
484
- transition offline: :charging
485
- end
486
-
487
- event :teleport do
488
- transition ready: :teleporting
489
- end
490
- end
491
-
492
- # Weapons remain synchronous for safety
493
- state_machine :weapons, initial: :disarmed do
494
- event :arm do
495
- transition disarmed: :armed
496
- end
497
- end
498
- end
499
- ```
500
-
501
- ## Async Event Methods
502
-
503
- Async-enabled machines automatically generate async versions of event methods:
504
-
505
- ```ruby
506
- drone = AutonomousDrone.new
507
-
508
- # Within an Async context
509
- Async do
510
- # Async event firing - returns Async::Task
511
- task = drone.launch_async
512
- result = task.wait # => #<StateMachines::Transition ...>
513
-
514
- # Bang methods for strict error handling
515
- drone.power_up_async! # => Async::Task (raises on failure)
516
-
517
- # Generic async event firing
518
- drone.fire_event_async(:teleport) # => Async::Task
519
- end
520
-
521
- # Outside Async context - raises error
522
- drone.launch_async # => RuntimeError: launch_async must be called within an Async context
523
- ```
524
-
525
- ## Thread Safety
526
-
527
- Async state machines use enterprise-grade thread safety with `concurrent-ruby`:
528
-
529
- ```ruby
530
- # Concurrent operations are automatically thread-safe
531
- threads = []
532
- 10.times do
533
- threads << Thread.new do
534
- Async do
535
- drone.launch_async.wait
536
- drone.land_async.wait
537
- end
538
- end
539
- end
540
- threads.each(&:join)
541
- ```
542
-
543
- ## Performance Considerations
544
-
545
- * **Thread Safety**: Uses `Concurrent::ReentrantReadWriteLock` for optimal read/write performance.
546
- * **Memory**: Each async-enabled object gets its own mutex (lazy-loaded).
547
- * **Marshalling**: Objects with async state machines can be serialized (mutex excluded/recreated).
548
- * **Mixed Mode**: You can mix async and sync state machines in the same class.
549
-
550
- ## Dependencies
551
-
552
- Async functionality requires:
553
-
554
- ```ruby
555
- # Gemfile (automatically scoped to MRI Ruby)
556
- platform :ruby do
557
- gem 'async', '>= 2.25.0'
558
- gem 'concurrent-ruby', '>= 1.3.5'
559
- end
560
- ```
561
-
562
- *Note: These gems are only installed on supported platforms. JRuby/TruffleRuby won't attempt installation.*
454
+ Extensions plug into machine hooks: `Machine#claims_transitions?` makes `TransitionCollection#perform`
455
+ claim the machine's attribute before performing (concurrent transitions out of one state then perform once,
456
+ the others are refused as `:contended`); `Machine#creation_options` / `Machine#after_definition` let a new
457
+ machine accept an extension's option (from the caller or the integration's defaults), and
458
+ `Machine#reopen_options` / `Machine#reopen` let a reopened machine accept it.
563
459
 
564
460
  ```ruby
565
461
  # Human-friendly names can be accessed for states/events
@@ -108,6 +108,18 @@ module StateMachines
108
108
  # See StateMachines::Branch for more information.
109
109
  attr_reader :branch
110
110
 
111
+ # The methods this callback runs, as configured: Symbols / Strings naming
112
+ # methods on the object, and the user's own Procs and Methods, in order
113
+ # (positional arguments, then +:do+, then the block). With
114
+ # +bind_to_object+ the Procs are still the user's own, so their identity,
115
+ # +source_location+ and +inspect+ describe the user's code. Frozen.
116
+ #
117
+ # callback = StateMachines::Callback.new(:before, :log, do: ->(vehicle) {})
118
+ # callback.callables # => [:log, #<Proc:0x...(lambda)>]
119
+ def callables
120
+ @methods
121
+ end
122
+
111
123
  # Creates a new callback that can get called based on the configured
112
124
  # options.
113
125
  #
@@ -134,11 +146,13 @@ module StateMachines
134
146
 
135
147
  options = { bind_to_object: self.class.bind_to_object, terminator: self.class.terminator }.merge(options)
136
148
 
137
- # Proxy lambda blocks so that they're bound to the object
149
+ # Blocks bound to the object run through a proxy, but @methods keeps the
150
+ # user's own blocks: their identity, source_location and inspect are
151
+ # what introspection and renderers report, not the proxy's
138
152
  bind_to_object = options.delete(:bind_to_object)
139
- @methods.map! do |method|
140
- bind_to_object && method.is_a?(Proc) ? bound_method(method) : method
141
- end
153
+ @bound_methods = {}.compare_by_identity
154
+ @methods.each { |method| @bound_methods[method] ||= bound_method(method) if bind_to_object && method.is_a?(Proc) }
155
+ @methods.freeze
142
156
 
143
157
  @terminator = options.delete(:terminator)
144
158
  @branch = Branch.new(options)
@@ -182,7 +196,7 @@ module StateMachines
182
196
  current_method = @methods[index]
183
197
  if current_method
184
198
  yielded = false
185
- evaluate_method(object, current_method, *) do
199
+ evaluate_method(object, invoker(current_method), *) do
186
200
  yielded = true
187
201
  run_methods(object, context, index + 1, *, &)
188
202
  end
@@ -193,12 +207,18 @@ module StateMachines
193
207
  end
194
208
  else
195
209
  @methods.each do |method|
196
- result = evaluate_method(object, method, *)
210
+ result = evaluate_method(object, invoker(method), *)
197
211
  throw :halt if @terminator&.call(result)
198
212
  end
199
213
  end
200
214
  end
201
215
 
216
+ # The callable to evaluate for a configured method: its bound proxy when
217
+ # the callback binds blocks to the object, otherwise the method itself
218
+ def invoker(method)
219
+ @bound_methods.fetch(method, method)
220
+ end
221
+
202
222
  # Generates a method that can be bound to the object being transitioned
203
223
  # when the callback is invoked
204
224
  def bound_method(block)
@@ -146,7 +146,18 @@ module StateMachines
146
146
  end
147
147
  end
148
148
 
149
- # A method was called in an invalid state context
150
- 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
151
162
  end
152
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
@@ -225,8 +225,10 @@ module StateMachines
225
225
  # - :halted - a before_transition or around_transition callback halted the
226
226
  # transition
227
227
  # - :action_failed - the machine's action (e.g. save) did not succeed
228
- # - :contended - in async mode, a concurrent transition held or moved the
229
- # attribute first
228
+ # - :contended - a concurrent transition held or moved the attribute
229
+ # first; only on machines that claim their transitions (see
230
+ # {StateMachines::Machine#claims_transitions?}), such as async mode
231
+ # machines of state_machines-async
230
232
  #
231
233
  # When the event was fired in parallel with others (see
232
234
  # {StateMachines::InstanceMethods#fire_events}), only the events that caused
@@ -22,9 +22,9 @@ module StateMachines
22
22
  end
23
23
 
24
24
  module InstanceMethods
25
- # Per-object concurrency state, created on demand: the lock and the
26
- # transition claims. Never copied nor marshalled.
27
- TRANSIENT_VARIABLES = %i[@_state_machine_mutex @_state_machine_transition_claims].freeze
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
28
 
29
29
  # Runs one or more events in parallel. All events will run through the
30
30
  # following steps:
@@ -147,8 +147,8 @@ module StateMachines
147
147
 
148
148
  # A copy (+dup+ / +clone+) has made no attempt to fire an event, so it
149
149
  # starts with no refusal reasons instead of sharing the original's. It
150
- # also gets its own lock and transition claims (created on demand)
151
- # instead of sharing the original's.
150
+ # also gets its own transition claims (created on demand) instead of
151
+ # sharing the original's.
152
152
  #
153
153
  # A class defining its own +initialize_copy+ must call +super+.
154
154
  #
@@ -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
@@ -3,9 +3,10 @@
3
3
  module StateMachines
4
4
  class Machine
5
5
  module ClassMethods
6
- # Options a reopened machine accepts; the others only apply when it is
7
- # created.
8
- REOPEN_OPTIONS = %i[initial async].freeze
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
9
10
 
10
11
  # Attempts to find or create a state machine for the given class. For
11
12
  # example,
@@ -19,7 +20,8 @@ module StateMachines
19
20
  # superclasses, then a copy of that machine will be created and stored
20
21
  # in the new owner class (the original will remain unchanged).
21
22
  #
22
- # Reopening an existing machine applies +:initial+ and +:async+;
23
+ # Reopening an existing machine applies the options in
24
+ # Machine#reopen_options (+:initial+, plus any a loaded extension adds);
23
25
  # any other option raises ArgumentError instead of being ignored.
24
26
  def find_or_create(owner_class, *args, &)
25
27
  options = args.last.is_a?(Hash) ? args.pop : {}
@@ -31,10 +33,12 @@ module StateMachines
31
33
  owner_class.state_machines.values.first))) || nil
32
34
 
33
35
  if machine
34
- unsupported = options.keys - REOPEN_OPTIONS
36
+ reopenable = machine.reopen_options
37
+ unsupported = options.keys - reopenable
38
+ assert_extensions_loaded!(unsupported)
35
39
  unless unsupported.empty?
36
40
  raise ArgumentError, "Cannot change #{unsupported.map(&:inspect).join(', ')} of existing state machine " \
37
- "#{name.inspect} on #{owner_class}; reopening it accepts only :initial and :async"
41
+ "#{name.inspect} on #{owner_class}; reopening it accepts only #{reopenable.map(&:inspect).join(', ')}"
38
42
  end
39
43
 
40
44
  # Only create a new copy if changes are being made to the machine in
@@ -43,8 +47,7 @@ module StateMachines
43
47
  machine = machine.clone
44
48
  machine.owner_class = owner_class
45
49
  end
46
- machine.initial_state = options[:initial] if options.include?(:initial)
47
- machine.configure_async_mode!(options[:async]) if options.include?(:async)
50
+ machine.reopen(options)
48
51
 
49
52
  # Evaluate DSL
50
53
  machine.instance_eval(&) if block_given?
@@ -60,6 +63,22 @@ module StateMachines
60
63
  raise NotImplementedError
61
64
  end
62
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
+
63
82
  # Default messages to use for validation errors in ORM integrations
64
83
  # Thread-safe access via atomic operations on simple values
65
84
  attr_accessor :ignore_method_conflicts
@@ -15,14 +15,17 @@ module StateMachines
15
15
  end
16
16
 
17
17
  # Validate options including integration-specific options
18
- valid_keys = %i[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
24
25
 
25
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)
26
29
  end
27
30
 
28
31
  # Add machine-wide defaults
@@ -30,6 +33,9 @@ module StateMachines
30
33
 
31
34
  # Set machine configuration
32
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')
33
39
  @attribute = options[:attribute] || @name
34
40
  @events = EventCollection.new(self)
35
41
  @states = StateCollection.new(self)
@@ -40,7 +46,6 @@ module StateMachines
40
46
  @use_transactions = options[:use_transactions]
41
47
  @initialize_state = options[:initialize]
42
48
  @action_hook_defined = false
43
- @async_requested = options[:async]
44
49
  @integration_options = @integration ? options.slice(*@integration.integration_options).freeze : {}.freeze
45
50
 
46
51
  self.owner_class = owner_class
@@ -56,8 +61,7 @@ module StateMachines
56
61
  # Evaluate DSL
57
62
  instance_eval(&) if block_given?
58
63
 
59
- # Configure async mode if requested, after owner_class is set and DSL is evaluated
60
- configure_async_mode!(true) if @async_requested
64
+ after_definition(options)
61
65
 
62
66
  self.initial_state = options[:initial] unless sibling_machines.any?
63
67
  end
@@ -73,8 +77,6 @@ module StateMachines
73
77
  @states = @states.dup
74
78
  @states.machine = self
75
79
  @callbacks = { before: @callbacks[:before].dup, after: @callbacks[:after].dup, failure: @callbacks[:failure].dup }
76
- @async_requested = orig.instance_variable_get(:@async_requested)
77
- @async_mode_enabled = orig.instance_variable_get(:@async_mode_enabled)
78
80
  end
79
81
 
80
82
  # Sets the class which is the owner of this state machine. Any methods
@@ -30,22 +30,35 @@ module StateMachines
30
30
  # Adds reader/writer methods for accessing the state attribute
31
31
  def define_state_accessor
32
32
  attribute = self.attribute
33
+ reader = !owner_class_ancestor_has_method?(:instance, attribute)
34
+ writer = !owner_class_ancestor_has_method?(:instance, "#{attribute}=")
35
+ unless ivar_name?(attribute)
36
+ # attr_reader / attr_writer store in @<attribute>, so core cannot
37
+ # define them; fine only if the owner class defines both itself
38
+ return if owner_class_has_method?(:instance, attribute) && owner_class_has_method?(:instance, "#{attribute}=")
39
+
40
+ raise_invalid_ivar_name(attribute, 'state machine attribute')
41
+ end
33
42
 
34
- @helper_modules[:instance].class_eval { attr_reader attribute } unless owner_class_ancestor_has_method?(:instance, attribute)
35
- @helper_modules[:instance].class_eval { attr_writer attribute } unless owner_class_ancestor_has_method?(:instance, "#{attribute}=")
43
+ @helper_modules[:instance].send(:attr_reader, attribute) if reader
44
+ @helper_modules[:instance].send(:attr_writer, attribute) if writer
36
45
  end
37
46
 
38
47
  # Adds predicate method to the owner class for determining the name of the
39
48
  # current state
40
49
  def define_state_predicate
41
- # Interpolated into the helper source, so it must be a literal boolean
42
- # (the finder answers the ancestor owning the method)
43
- call_super = owner_class_ancestor_has_method?(:instance, "#{name}?") ? true : false # rubocop:disable Style/IfWithBooleanLiteralBranches
44
- define_helper :instance, <<-END_EVAL, __FILE__, __LINE__ + 1
45
- def #{name}?(*args)
46
- args.empty? && (#{call_super} || defined?(super)) ? super : self.class.state_machine(#{name.inspect}).states.matches?(self, *args)
47
- end
48
- END_EVAL
50
+ machine_name = name
51
+ call_super = owner_class_ancestor_has_method?(:instance, "#{name}?")
52
+ # Defined directly rather than through define_helper, which would skip
53
+ # it with a conflict warning: this predicate deliberately wraps an
54
+ # inherited one, deferring to it when called without arguments
55
+ @helper_modules[:instance].send(:define_method, "#{name}?") do |*args|
56
+ if args.empty? && (call_super || defined?(super))
57
+ super()
58
+ else
59
+ self.class.state_machine(machine_name).states.matches?(self, *args)
60
+ end
61
+ end
49
62
  end
50
63
 
51
64
  # Adds helper methods for getting information about this state machine's
@@ -85,9 +98,9 @@ module StateMachines
85
98
  end
86
99
 
87
100
  event_transition_attribute = attribute(:event_transition)
88
- define_helper :instance, <<-END_EVAL, __FILE__, __LINE__ + 1
89
- protected; attr_accessor #{event_transition_attribute.inspect}
90
- END_EVAL
101
+ helper = @helper_modules[:instance]
102
+ helper.send(:attr_accessor, event_transition_attribute)
103
+ helper.send(:protected, event_transition_attribute, :"#{event_transition_attribute}=")
91
104
  end
92
105
 
93
106
  # Adds helper methods for getting information about this state machine's
@@ -271,14 +271,15 @@ module StateMachines
271
271
  # === Invalid behaviors
272
272
  #
273
273
  # If a specific behavior has not been defined for a state, then a
274
- # NoMethodError exception will be raised, indicating that that method would
275
- # not normally exist for an object with that state.
274
+ # StateMachines::InvalidContext, which is a NoMethodError, will be raised,
275
+ # indicating that that method would not normally exist for an object with
276
+ # that state.
276
277
  #
277
278
  # Using the example from before:
278
279
  #
279
280
  # vehicle = Vehicle.new
280
281
  # vehicle.state = 'backing_up'
281
- # vehicle.speed # => NoMethodError: undefined method 'speed' for #<Vehicle:0xb7d296ac> in state "backing_up"
282
+ # vehicle.speed # => StateMachines::InvalidContext: State :backing_up for :state is not a valid context for calling #speed
282
283
  #
283
284
  # === Using matchers
284
285
  #
@@ -3,8 +3,32 @@
3
3
  module StateMachines
4
4
  class Machine
5
5
  module Utilities
6
+ # Probed (never written) to ask Ruby whether a name is a legal instance
7
+ # variable name, which also makes it a legal attr_accessor name
8
+ IVAR_PROBE = Object.new.freeze
9
+ private_constant :IVAR_PROBE
10
+
6
11
  protected
7
12
 
13
+ # Whether +name+ makes a valid instance variable name (@name)
14
+ def ivar_name?(name)
15
+ IVAR_PROBE.instance_variable_defined?(:"@#{name}")
16
+ true
17
+ rescue NameError
18
+ false
19
+ end
20
+
21
+ # Raises an ArgumentError unless +name+ makes a valid instance variable
22
+ # name, so a bad name fails where it is given rather than later from
23
+ # attr_accessor or instance_variable_get
24
+ def assert_ivar_name!(name, role)
25
+ raise_invalid_ivar_name(name, role) unless ivar_name?(name)
26
+ end
27
+
28
+ def raise_invalid_ivar_name(name, role)
29
+ raise ArgumentError, "#{name.inspect} is not a valid #{role}: it must be usable as an instance variable name (@#{name})"
30
+ end
31
+
8
32
  # Looks up other machines that have been defined in the owner class and
9
33
  # are targeting the same attribute as this machine. When accessing
10
34
  # sibling machines, they will be automatically copied for the current