state_machines 0.302.0 → 0.304.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 +4 -4
- data/README.md +61 -1
- data/lib/state_machines/branch.rb +21 -0
- data/lib/state_machines/callback.rb +26 -6
- data/lib/state_machines/error.rb +13 -2
- data/lib/state_machines/eval_helpers.rb +31 -18
- data/lib/state_machines/event.rb +60 -2
- data/lib/state_machines/machine/action_hooks.rb +13 -10
- data/lib/state_machines/machine/callbacks.rb +15 -0
- data/lib/state_machines/machine/configuration.rb +3 -0
- data/lib/state_machines/machine/helper_generators.rb +26 -13
- data/lib/state_machines/machine/state_methods.rb +4 -3
- data/lib/state_machines/machine/utilities.rb +24 -0
- data/lib/state_machines/machine.rb +0 -2
- data/lib/state_machines/node_collection.rb +26 -23
- data/lib/state_machines/state.rb +66 -31
- data/lib/state_machines/state_collection.rb +10 -2
- data/lib/state_machines/state_context.rb +6 -1
- data/lib/state_machines/test_helper.rb +132 -101
- data/lib/state_machines/transition.rb +108 -232
- data/lib/state_machines/transition_collection.rb +6 -14
- data/lib/state_machines/version.rb +1 -1
- metadata +1 -2
- data/lib/state_machines/machine/validation.rb +0 -39
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 338ccdcb73c4d48a79f2c315c7d4d75a7c536cc14e14f317f3ae143714898d8c
|
|
4
|
+
data.tar.gz: a69ab4c2ed3017be001800afd17ab3f5846487f2fb72a98ce072a361b43e1e31
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 89ed8906794be85e5a5dd93f157c486e4390196ff8413df790705f684ccf16fb59007445c74e44ad73808303a52286f31d1e4cbf6b7580daa346f6c30b3e9cf9
|
|
7
|
+
data.tar.gz: eb1e74b5b5509eda7ac188b8a7dc46b102084befb79623fc5656c8c5d6b715faf783af9e986d7eb551216c0f05589142637670da4cb9c4f94f1f1adcb4e4e381
|
data/README.md
CHANGED
|
@@ -211,7 +211,8 @@ vehicle # => #<Vehicle:0xb7cf4eac @state="first_gear", @
|
|
|
211
211
|
vehicle.fire_state_event(:shift_up) # => #<StateMachines::Transition attribute=:state event=:shift_up ...>
|
|
212
212
|
|
|
213
213
|
# Call state-driven behavior that's undefined for the state raises a NoMethodError
|
|
214
|
-
|
|
214
|
+
# (StateMachines::InvalidContext)
|
|
215
|
+
vehicle.speed # => StateMachines::InvalidContext: State :second_gear for :state is not a valid context for calling #speed
|
|
215
216
|
vehicle # => #<Vehicle:0xb7cf4eac @state="second_gear", @seatbelt_on=true>
|
|
216
217
|
|
|
217
218
|
# The bang (!) operator can raise exceptions if the event fails
|
|
@@ -350,6 +351,65 @@ end
|
|
|
350
351
|
The reader is also available on the event itself:
|
|
351
352
|
`Vehicle.state_machine.events[:park].refusal(vehicle)`.
|
|
352
353
|
|
|
354
|
+
## Branch Callbacks
|
|
355
|
+
|
|
356
|
+
A `transition` can carry its own `before:`, `after:` and `around:` callbacks.
|
|
357
|
+
They run only when that transition is the branch chosen for the event, so they
|
|
358
|
+
share its guards without repeating them in an `after_transition`:
|
|
359
|
+
|
|
360
|
+
```ruby
|
|
361
|
+
class Vehicle
|
|
362
|
+
state_machine initial: :parked do
|
|
363
|
+
event :ignite do
|
|
364
|
+
transition parked: :idling, if: :warm?
|
|
365
|
+
transition parked: :preheating, after: :start_glow_plugs
|
|
366
|
+
transition stalled: :idling, before: :check_battery, after: %i[log_restart notify_owner]
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
end
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
Each takes what `after_transition`'s `do:` takes: a method name (Symbol or
|
|
373
|
+
String), an Array of them, or a Proc/Method. They are ordinary callbacks:
|
|
374
|
+
`bind_to_object`, the integration's terminator and `throw :halt` behave as for
|
|
375
|
+
`before_transition`/`after_transition`.
|
|
376
|
+
|
|
377
|
+
They wrap closest to the state change: the machine's `before_transition` and
|
|
378
|
+
`around_transition` callbacks run first, then the branch's `before:`/`around:`
|
|
379
|
+
(in the order written), then the change; then the branch's `after:`, then the
|
|
380
|
+
machine's `after_transition`. A branch `after:` runs only when the transition
|
|
381
|
+
succeeds; there is no branch-level `after_failure` (use `after_failure`).
|
|
382
|
+
`assert_before_transition`/`assert_after_transition` see branch callbacks, matched
|
|
383
|
+
against their branch.
|
|
384
|
+
|
|
385
|
+
A transition takes its callback chain when it starts: a `before_transition`
|
|
386
|
+
registered while that chain is running applies from the next transition on.
|
|
387
|
+
|
|
388
|
+
Validating before saving (ActiveModel and ActiveRecord with a pending event, e.g.
|
|
389
|
+
`valid?` before `save`) runs a preview of the transition: every
|
|
390
|
+
`before_transition` callback, skipping the `around_transition` callbacks (not
|
|
391
|
+
entered, their conditions not evaluated), then the validation in the new state,
|
|
392
|
+
and no after callbacks. Validation therefore sees everything the save's before
|
|
393
|
+
callbacks set. The save does not repeat those before callbacks; its around
|
|
394
|
+
callbacks wrap the save alone, on its own stack. So when `valid?` ran first, a
|
|
395
|
+
`before_transition` declared after an `around_transition` has already run outside
|
|
396
|
+
that around; a save without a prior `valid?` interleaves the callbacks exactly as
|
|
397
|
+
declared. An around callback never stays suspended between two calls.
|
|
398
|
+
|
|
399
|
+
`before`, `after`, `around` and `do` are reserved keys in a transition's hash, like
|
|
400
|
+
`from`, `to`, `if` and `unless`. `do:` is refused, since a branch has three kinds
|
|
401
|
+
of callbacks. A state named `:after` (or `:before`, `:around`) is written with
|
|
402
|
+
`from:`/`to:`:
|
|
403
|
+
|
|
404
|
+
```ruby
|
|
405
|
+
transition from: :after, to: :parked
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
The branches keep their callbacks in `Branch#callbacks`
|
|
409
|
+
(`Vehicle.state_machine.events[:ignite].branches.last.callbacks`), as
|
|
410
|
+
`StateMachines::Callback` objects with `#type` and `#callables`, for renderers
|
|
411
|
+
and tooling.
|
|
412
|
+
|
|
353
413
|
# Coordinated State Management
|
|
354
414
|
|
|
355
415
|
State machines can coordinate with each other using state guards, allowing transitions to depend on the state of other state machines within the same object. This enables complex system modeling where components are interdependent.
|
|
@@ -37,8 +37,29 @@ module StateMachines
|
|
|
37
37
|
# * +to+ / +except_to+
|
|
38
38
|
attr_reader :known_states
|
|
39
39
|
|
|
40
|
+
# The callbacks scoped to this branch by an event's
|
|
41
|
+
# <tt>transition ..., before: / after: / around:</tt>, in the order they
|
|
42
|
+
# were given, as StateMachines::Callback instances (see Callback#type and
|
|
43
|
+
# Callback#callables). They run only when this branch is the one selected
|
|
44
|
+
# for a transition, so this branch's guards apply to them. Frozen; empty
|
|
45
|
+
# for branches without callbacks.
|
|
46
|
+
attr_reader :callbacks
|
|
47
|
+
|
|
48
|
+
# Key under which Event#transition hands over the branch callbacks: not a
|
|
49
|
+
# Symbol, so no state name can collide with it
|
|
50
|
+
CALLBACKS = Object.new.freeze
|
|
51
|
+
private_constant :CALLBACKS
|
|
52
|
+
|
|
53
|
+
# Builds the options hash for a branch with callbacks (used by Event)
|
|
54
|
+
def self.options_with_callbacks(options, callbacks) # :nodoc:
|
|
55
|
+
options.merge(CALLBACKS => callbacks)
|
|
56
|
+
end
|
|
57
|
+
|
|
40
58
|
# Creates a new branch
|
|
41
59
|
def initialize(options = {}) # :nodoc:
|
|
60
|
+
options = options.dup
|
|
61
|
+
@callbacks = (options.delete(CALLBACKS) || []).freeze
|
|
62
|
+
|
|
42
63
|
# Build conditionals
|
|
43
64
|
@if_condition = options.delete(:if)
|
|
44
65
|
@unless_condition = options.delete(:unless)
|
|
@@ -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
|
-
#
|
|
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
|
-
@
|
|
140
|
-
|
|
141
|
-
|
|
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)
|
data/lib/state_machines/error.rb
CHANGED
|
@@ -146,7 +146,18 @@ module StateMachines
|
|
|
146
146
|
end
|
|
147
147
|
end
|
|
148
148
|
|
|
149
|
-
# A method was called
|
|
150
|
-
|
|
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
|
-
|
|
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
|
-
#
|
|
198
|
-
# This is a basic safety check
|
|
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
|
-
|
|
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
|
data/lib/state_machines/event.rb
CHANGED
|
@@ -121,14 +121,45 @@ module StateMachines
|
|
|
121
121
|
#
|
|
122
122
|
# See StateMachines::Machine#transition for a description of the possible
|
|
123
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>.
|
|
124
138
|
def transition(options)
|
|
125
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
|
|
126
157
|
|
|
127
158
|
# Only a certain subset of explicit options are allowed for transition
|
|
128
159
|
# requirements
|
|
129
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?
|
|
130
161
|
|
|
131
|
-
branches << branch = Branch.new(options.merge(on: name))
|
|
162
|
+
branches << branch = Branch.new(Branch.options_with_callbacks(options.merge(on: name), callbacks))
|
|
132
163
|
@known_states |= branch.known_states
|
|
133
164
|
branch
|
|
134
165
|
end
|
|
@@ -174,7 +205,7 @@ module StateMachines
|
|
|
174
205
|
match[:to].filter(values).first
|
|
175
206
|
end
|
|
176
207
|
|
|
177
|
-
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)
|
|
178
209
|
end
|
|
179
210
|
|
|
180
211
|
# No transition matched
|
|
@@ -368,5 +399,32 @@ module StateMachines
|
|
|
368
399
|
object.send(qualified_name, *args, **kwargs) || raise(StateMachines::InvalidTransition.new(object, machine, name))
|
|
369
400
|
end
|
|
370
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
|
|
371
429
|
end
|
|
372
430
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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)
|
|
@@ -33,6 +33,9 @@ module StateMachines
|
|
|
33
33
|
|
|
34
34
|
# Set machine configuration
|
|
35
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')
|
|
36
39
|
@attribute = options[:attribute] || @name
|
|
37
40
|
@events = EventCollection.new(self)
|
|
38
41
|
@states = StateCollection.new(self)
|
|
@@ -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].
|
|
35
|
-
@helper_modules[:instance].
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
|
275
|
-
# not normally exist for an object with
|
|
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 # =>
|
|
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
|
|
@@ -4,7 +4,6 @@ require_relative 'options_validator'
|
|
|
4
4
|
require_relative 'machine/class_methods'
|
|
5
5
|
require_relative 'machine/utilities'
|
|
6
6
|
require_relative 'machine/parsing'
|
|
7
|
-
require_relative 'machine/validation'
|
|
8
7
|
require_relative 'machine/helper_generators'
|
|
9
8
|
require_relative 'machine/action_hooks'
|
|
10
9
|
require_relative 'machine/scoping'
|
|
@@ -421,7 +420,6 @@ module StateMachines
|
|
|
421
420
|
include MatcherHelpers
|
|
422
421
|
include Utilities
|
|
423
422
|
include Parsing
|
|
424
|
-
include Validation
|
|
425
423
|
include HelperGenerators
|
|
426
424
|
include ActionHooks
|
|
427
425
|
include Scoping
|
|
@@ -4,8 +4,11 @@ require_relative 'options_validator'
|
|
|
4
4
|
|
|
5
5
|
module StateMachines
|
|
6
6
|
# Represents a collection of nodes in a state machine, be it events or states.
|
|
7
|
-
#
|
|
8
|
-
#
|
|
7
|
+
# Lookups in a string-keyed index (by default, every index) treat a key and
|
|
8
|
+
# its string form as the same key (:parked, 'parked', and 10 / '10' / :'10'
|
|
9
|
+
# for numeric keys). The one exception is nil: it is only ever found by nil,
|
|
10
|
+
# since nil.to_s is '' and would otherwise collide with a node keyed by :"" or
|
|
11
|
+
# ''. Other indices only find a node by an eql? key.
|
|
9
12
|
class NodeCollection
|
|
10
13
|
include Enumerable
|
|
11
14
|
|
|
@@ -19,17 +22,22 @@ module StateMachines
|
|
|
19
22
|
# * <tt>:index</tt> - One or more attributes to automatically generate
|
|
20
23
|
# hashed indices for in order to perform quick lookups. Default is to
|
|
21
24
|
# index by the :name attribute
|
|
25
|
+
# * <tt>:string_keys</tt> - The indices that also find a node by the string
|
|
26
|
+
# form of its key. Default is every index
|
|
22
27
|
def initialize(machine, options = {})
|
|
23
|
-
StateMachines::OptionsValidator.assert_valid_keys!(options, :index)
|
|
28
|
+
StateMachines::OptionsValidator.assert_valid_keys!(options, :index, :string_keys)
|
|
24
29
|
options = { index: :name }.merge(options)
|
|
25
30
|
|
|
26
31
|
@machine = machine
|
|
27
32
|
@nodes = []
|
|
28
33
|
@index_names = Array(options[:index])
|
|
34
|
+
@string_keys = Array(options.fetch(:string_keys, @index_names))
|
|
35
|
+
unknown = @string_keys - @index_names
|
|
36
|
+
raise ArgumentError, "Invalid string_keys: #{unknown.inspect} not in the indices" if unknown.any?
|
|
37
|
+
|
|
29
38
|
@indices = @index_names.each_with_object({}) do |name, indices|
|
|
30
39
|
indices[name] = {}
|
|
31
|
-
indices[:"#{name}_to_s"] = {}
|
|
32
|
-
indices[:"#{name}_to_sym"] = {}
|
|
40
|
+
indices[:"#{name}_to_s"] = {} if @string_keys.include?(name)
|
|
33
41
|
end
|
|
34
42
|
@default_index = Array(options[:index]).first
|
|
35
43
|
@contexts = []
|
|
@@ -146,9 +154,7 @@ module StateMachines
|
|
|
146
154
|
# If the key cannot be found, then nil will be returned.
|
|
147
155
|
def [](key, index_name = @default_index)
|
|
148
156
|
index(index_name)[key] ||
|
|
149
|
-
index(:"#{index_name}_to_s")[key.to_s]
|
|
150
|
-
(to_sym?(key) && index(:"#{index_name}_to_sym")[:"#{key}"]) ||
|
|
151
|
-
nil
|
|
157
|
+
(string_key?(index_name, key) ? index(:"#{index_name}_to_s")[key.to_s] : nil)
|
|
152
158
|
end
|
|
153
159
|
|
|
154
160
|
# Gets the node indexed by the given key. By default, this will look up the
|
|
@@ -182,24 +188,26 @@ module StateMachines
|
|
|
182
188
|
node.send(attribute)
|
|
183
189
|
end
|
|
184
190
|
|
|
185
|
-
#
|
|
186
|
-
#
|
|
191
|
+
# Whether the key has a string version in the given index. A nil key has
|
|
192
|
+
# none: nil.to_s is '', which would make nil and :"" the same key.
|
|
193
|
+
def string_key?(name, key)
|
|
194
|
+
!key.nil? && @string_keys.include?(name)
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# Adds the given key / node combination to an index, including its string
|
|
198
|
+
# version where the index has one
|
|
187
199
|
def add_to_index(name, key, node)
|
|
188
200
|
index(name)[key] = node
|
|
189
|
-
index(:"#{name}_to_s")[key.to_s] = node
|
|
190
|
-
index(:"#{name}_to_sym")[:"#{key}"] = node if to_sym?(key)
|
|
201
|
+
index(:"#{name}_to_s")[key.to_s] = node if string_key?(name, key)
|
|
191
202
|
end
|
|
192
203
|
|
|
193
|
-
# Removes the given key from an index, including
|
|
194
|
-
# versions of the index
|
|
204
|
+
# Removes the given key from an index, including its string version
|
|
195
205
|
def remove_from_index(name, key)
|
|
196
206
|
index(name).delete(key)
|
|
197
|
-
index(:"#{name}_to_s").delete(key.to_s)
|
|
198
|
-
index(:"#{name}_to_sym").delete(:"#{key}") if to_sym?(key)
|
|
207
|
+
index(:"#{name}_to_s").delete(key.to_s) if string_key?(name, key)
|
|
199
208
|
end
|
|
200
209
|
|
|
201
|
-
# Updates the node for the given index, including
|
|
202
|
-
# versions of the index
|
|
210
|
+
# Updates the node for the given index, including its string version
|
|
203
211
|
def update_index(name, node)
|
|
204
212
|
index = self.index(name)
|
|
205
213
|
old_key = index.key(node)
|
|
@@ -212,11 +220,6 @@ module StateMachines
|
|
|
212
220
|
add_to_index(name, new_key, node)
|
|
213
221
|
end
|
|
214
222
|
|
|
215
|
-
# Determines whether the given value can be converted to a symbol
|
|
216
|
-
def to_sym?(value)
|
|
217
|
-
"#{value}" != ''
|
|
218
|
-
end
|
|
219
|
-
|
|
220
223
|
# Evaluates the given context for a particular node. This will only
|
|
221
224
|
# evaluate the context if the node matches.
|
|
222
225
|
def eval_context(context, node)
|