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.
- checksums.yaml +4 -4
- data/README.md +226 -125
- data/lib/state_machines/branch.rb +56 -22
- data/lib/state_machines/callback.rb +28 -8
- data/lib/state_machines/core.rb +1 -0
- data/lib/state_machines/error.rb +50 -2
- data/lib/state_machines/eval_helpers.rb +31 -18
- data/lib/state_machines/event.rb +187 -4
- data/lib/state_machines/event_collection.rb +6 -1
- data/lib/state_machines/extensions.rb +22 -0
- data/lib/state_machines/helper_module.rb +1 -0
- data/lib/state_machines/machine/action_hooks.rb +13 -10
- data/lib/state_machines/machine/callbacks.rb +15 -0
- data/lib/state_machines/machine/class_methods.rb +34 -3
- data/lib/state_machines/machine/configuration.rb +12 -8
- data/lib/state_machines/machine/event_methods.rb +5 -0
- data/lib/state_machines/machine/helper_generators.rb +26 -11
- data/lib/state_machines/machine/state_methods.rb +4 -3
- data/lib/state_machines/machine/utilities.rb +25 -1
- data/lib/state_machines/machine.rb +62 -3
- data/lib/state_machines/machine_collection.rb +7 -6
- data/lib/state_machines/macro_methods.rb +4 -4
- data/lib/state_machines/node_collection.rb +26 -23
- data/lib/state_machines/path.rb +1 -0
- data/lib/state_machines/path_collection.rb +1 -0
- data/lib/state_machines/state.rb +66 -31
- data/lib/state_machines/state_collection.rb +10 -2
- data/lib/state_machines/state_context.rb +7 -1
- data/lib/state_machines/stdio_renderer.rb +8 -6
- data/lib/state_machines/syntax_validator.rb +3 -3
- data/lib/state_machines/test_helper.rb +309 -259
- data/lib/state_machines/transition.rb +136 -230
- data/lib/state_machines/transition_claim.rb +119 -0
- data/lib/state_machines/transition_collection.rb +147 -31
- data/lib/state_machines/version.rb +1 -1
- metadata +8 -15
- data/lib/state_machines/async_mode/async_event_extensions.rb +0 -49
- data/lib/state_machines/async_mode/async_events.rb +0 -286
- data/lib/state_machines/async_mode/async_machine.rb +0 -60
- data/lib/state_machines/async_mode/async_transition_collection.rb +0 -136
- data/lib/state_machines/async_mode/thread_safe_state.rb +0 -47
- data/lib/state_machines/async_mode.rb +0 -64
- data/lib/state_machines/machine/async_extensions.rb +0 -88
- data/lib/state_machines/machine/validation.rb +0 -39
|
@@ -30,20 +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
|
-
|
|
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
|
|
47
62
|
end
|
|
48
63
|
|
|
49
64
|
# Adds helper methods for getting information about this state machine's
|
|
@@ -83,9 +98,9 @@ module StateMachines
|
|
|
83
98
|
end
|
|
84
99
|
|
|
85
100
|
event_transition_attribute = attribute(:event_transition)
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
101
|
+
helper = @helper_modules[:instance]
|
|
102
|
+
helper.send(:attr_accessor, event_transition_attribute)
|
|
103
|
+
helper.send(:protected, event_transition_attribute, :"#{event_transition_attribute}=")
|
|
89
104
|
end
|
|
90
105
|
|
|
91
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
|
|
@@ -13,7 +37,7 @@ module StateMachines
|
|
|
13
37
|
# base class that may have originally defined the machine.
|
|
14
38
|
def sibling_machines
|
|
15
39
|
owner_class.state_machines.each_with_object([]) do |(name, machine), machines|
|
|
16
|
-
machines <<
|
|
40
|
+
machines << owner_class.state_machine(name) {} if machine.attribute == attribute && machine != self
|
|
17
41
|
end
|
|
18
42
|
end
|
|
19
43
|
|
|
@@ -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'
|
|
@@ -14,7 +13,6 @@ require_relative 'machine/event_methods'
|
|
|
14
13
|
require_relative 'machine/callbacks'
|
|
15
14
|
require_relative 'machine/rendering'
|
|
16
15
|
require_relative 'machine/integration'
|
|
17
|
-
require_relative 'machine/async_extensions'
|
|
18
16
|
require_relative 'syntax_validator'
|
|
19
17
|
|
|
20
18
|
module StateMachines
|
|
@@ -422,7 +420,6 @@ module StateMachines
|
|
|
422
420
|
include MatcherHelpers
|
|
423
421
|
include Utilities
|
|
424
422
|
include Parsing
|
|
425
|
-
include Validation
|
|
426
423
|
include HelperGenerators
|
|
427
424
|
include ActionHooks
|
|
428
425
|
include Scoping
|
|
@@ -476,6 +473,14 @@ module StateMachines
|
|
|
476
473
|
# Whether the machine will use transactions when firing events
|
|
477
474
|
attr_reader :use_transactions
|
|
478
475
|
|
|
476
|
+
# The options declared by the machine's integration (see
|
|
477
|
+
# StateMachines::Integrations::Base::ClassMethods#integration_options)
|
|
478
|
+
# that were passed when creating the machine. Available from
|
|
479
|
+
# +owner_class=+ onward.
|
|
480
|
+
#
|
|
481
|
+
# @return [Hash{Symbol => Object}] frozen option name => value
|
|
482
|
+
attr_reader :integration_options
|
|
483
|
+
|
|
479
484
|
# Defines a new helper method in an instance or class scope with the given
|
|
480
485
|
# name. If the method is already defined in the scope, then this will not
|
|
481
486
|
# override it.
|
|
@@ -589,11 +594,65 @@ module StateMachines
|
|
|
589
594
|
@action_hook_defined || (!self_only && owner_class.state_machines.any? { |_name, machine| machine.action == action && machine != self && machine.action_hook?(true) })
|
|
590
595
|
end
|
|
591
596
|
|
|
597
|
+
# Whether objects may perform this machine's transitions concurrently, from
|
|
598
|
+
# several threads or fibers at once. When true,
|
|
599
|
+
# TransitionCollection#perform claims the machine's attribute on the
|
|
600
|
+
# object before performing (see StateMachines::TransitionClaim), so of
|
|
601
|
+
# concurrent transitions out of one state only the first is performed and
|
|
602
|
+
# the others are refused as :contended.
|
|
603
|
+
#
|
|
604
|
+
# The core's machines do not claim. An extension that performs
|
|
605
|
+
# transitions concurrently overrides this, as state_machines-async does
|
|
606
|
+
# for the machines it runs in async mode.
|
|
607
|
+
#
|
|
608
|
+
# @return [Boolean]
|
|
609
|
+
def claims_transitions?
|
|
610
|
+
false
|
|
611
|
+
end
|
|
612
|
+
|
|
613
|
+
# The options a new machine accepts, besides its integration's
|
|
614
|
+
# (StateMachines::Integrations::Base::ClassMethods#integration_options).
|
|
615
|
+
# An extension adding an option appends it here and applies it in
|
|
616
|
+
# #after_definition.
|
|
617
|
+
#
|
|
618
|
+
# @return [Array<Symbol>]
|
|
619
|
+
def creation_options
|
|
620
|
+
%i[attribute initial initialize action plural namespace integration messages use_transactions]
|
|
621
|
+
end
|
|
622
|
+
|
|
623
|
+
# The options a reopened machine accepts (see
|
|
624
|
+
# StateMachines::Machine.find_or_create); the others only apply when it is
|
|
625
|
+
# created. An extension adding a reopenable option appends it here and
|
|
626
|
+
# applies it in #reopen.
|
|
627
|
+
#
|
|
628
|
+
# @return [Array<Symbol>]
|
|
629
|
+
def reopen_options
|
|
630
|
+
%i[initial]
|
|
631
|
+
end
|
|
632
|
+
|
|
633
|
+
# Applies the options given when this machine is reopened, before the
|
|
634
|
+
# reopening block is evaluated.
|
|
635
|
+
#
|
|
636
|
+
# @param options [Hash] the options, limited to #reopen_options
|
|
637
|
+
# @return [void]
|
|
638
|
+
def reopen(options)
|
|
639
|
+
self.initial_state = options[:initial] if options.include?(:initial)
|
|
640
|
+
end
|
|
641
|
+
|
|
592
642
|
protected
|
|
593
643
|
|
|
594
644
|
# Runs additional initialization hooks. By default, this is a no-op.
|
|
595
645
|
def after_initialize; end
|
|
596
646
|
|
|
647
|
+
# Runs once a new machine's definition block has been evaluated, before
|
|
648
|
+
# its initial state is set, with its options: the caller's merged over
|
|
649
|
+
# the integration's defaults. By default, this is a no-op; an extension
|
|
650
|
+
# applies its #creation_options here.
|
|
651
|
+
#
|
|
652
|
+
# @param _options [Hash] the machine's options
|
|
653
|
+
# @return [void]
|
|
654
|
+
def after_definition(_options); end
|
|
655
|
+
|
|
597
656
|
# Always yields
|
|
598
657
|
def transaction(_object)
|
|
599
658
|
yield
|
|
@@ -61,15 +61,16 @@ module StateMachines
|
|
|
61
61
|
raise(InvalidEvent.new(object, event_name)) unless event
|
|
62
62
|
|
|
63
63
|
# Get the transition that will be performed for the event
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
64
|
+
transition = event.transition_for(object)
|
|
65
|
+
event.record_refusal(object, transition ? nil : event.refusal_without_transition(object))
|
|
66
|
+
event.on_failure(object) unless transition
|
|
67
67
|
transition
|
|
68
|
-
end
|
|
68
|
+
end
|
|
69
69
|
|
|
70
70
|
# Run the events in parallel only if valid transitions were found for
|
|
71
|
-
# all of them
|
|
72
|
-
|
|
71
|
+
# all of them. Otherwise only the events without a transition carry a
|
|
72
|
+
# refusal reason.
|
|
73
|
+
if transitions.all?
|
|
73
74
|
TransitionCollection.new(transitions, { use_transactions: resolve_use_transactions, actions: run_action }).perform
|
|
74
75
|
else
|
|
75
76
|
false
|
|
@@ -185,13 +185,13 @@ module StateMachines
|
|
|
185
185
|
#
|
|
186
186
|
# # Getting current event / transition availability
|
|
187
187
|
# vehicle.state_events # => [:park]
|
|
188
|
-
# vehicle.park # =>
|
|
188
|
+
# vehicle.park # => #<StateMachines::Transition attribute=:state event=:park ...>
|
|
189
189
|
# vehicle.state_events # => [:ignite]
|
|
190
190
|
# vehicle.state_events(:from => :idling) # => [:park]
|
|
191
191
|
# vehicle.state_events(:to => :parked) # => []
|
|
192
192
|
#
|
|
193
193
|
# vehicle.state_transitions # => [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>]
|
|
194
|
-
# vehicle.ignite # =>
|
|
194
|
+
# vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
|
|
195
195
|
# vehicle.state_transitions # => [#<StateMachines::Transition attribute=:state event=:park from="idling" from_name=:idling to="parked" to_name=:parked>]
|
|
196
196
|
#
|
|
197
197
|
# vehicle.state_transitions(:on => :ignite) # => []
|
|
@@ -207,7 +207,7 @@ module StateMachines
|
|
|
207
207
|
# # ]
|
|
208
208
|
#
|
|
209
209
|
# # Fire arbitrary events
|
|
210
|
-
# vehicle.fire_state_event(:park) # =>
|
|
210
|
+
# vehicle.fire_state_event(:park) # => #<StateMachines::Transition attribute=:state event=:park ...>
|
|
211
211
|
#
|
|
212
212
|
# == Attribute initialization
|
|
213
213
|
#
|
|
@@ -414,7 +414,7 @@ module StateMachines
|
|
|
414
414
|
#
|
|
415
415
|
# # Fire +ignite+ event directly
|
|
416
416
|
# vehicle = Vehicle.create # => #<Vehicle id=1 state="parked" alarm_state="active">
|
|
417
|
-
# vehicle.ignite # =>
|
|
417
|
+
# vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
|
|
418
418
|
# vehicle.state # => "idling"
|
|
419
419
|
# vehicle.alarm_state # => "active"
|
|
420
420
|
#
|
|
@@ -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)
|
data/lib/state_machines/path.rb
CHANGED
|
@@ -22,6 +22,7 @@ module StateMachines
|
|
|
22
22
|
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
|
|
23
23
|
# conditionals defined for each one
|
|
24
24
|
def initialize(object, machine, options = {})
|
|
25
|
+
super()
|
|
25
26
|
StateMachines::OptionsValidator.assert_valid_keys!(options, :target, :guard)
|
|
26
27
|
|
|
27
28
|
@object = object
|
|
@@ -27,6 +27,7 @@ module StateMachines
|
|
|
27
27
|
# * <tt>:guard</tt> - Whether to guard transitions with the if/unless
|
|
28
28
|
# conditionals defined for each one
|
|
29
29
|
def initialize(object, machine, options = {})
|
|
30
|
+
super()
|
|
30
31
|
options = { deep: false, from: machine.states.match!(object).name }.merge(options)
|
|
31
32
|
StateMachines::OptionsValidator.assert_valid_keys!(options, :from, :to, :deep, :guard)
|
|
32
33
|
|
data/lib/state_machines/state.rb
CHANGED
|
@@ -212,17 +212,30 @@ module StateMachines
|
|
|
212
212
|
context.class_eval(&)
|
|
213
213
|
new_methods = context_methods.to_a.reject { |(name, method)| old_methods[name] == method }
|
|
214
214
|
|
|
215
|
-
# Alias new methods so that the only execute when the object is in this
|
|
215
|
+
# Alias new methods so that the only execute when the object is in this
|
|
216
|
+
# state. define_method, not a def in evaluated source: the methods are
|
|
217
|
+
# the user's, under any name Ruby allows (:"do it", :[], :+).
|
|
218
|
+
machine_name = machine.name
|
|
219
|
+
state_name = name
|
|
216
220
|
new_methods.each do |(method_name, _method)|
|
|
217
221
|
context_name = context_name_for(method_name)
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
222
|
+
visibility = if context.private_method_defined?(method_name) then :private
|
|
223
|
+
elsif context.protected_method_defined?(method_name) then :protected
|
|
224
|
+
end
|
|
225
|
+
context.send(:alias_method, context_name, method_name)
|
|
226
|
+
context.send(:define_method, method_name) do |*args, **kwargs, &block|
|
|
227
|
+
state = self.class.state_machine(machine_name).states.fetch(state_name)
|
|
228
|
+
# Out of state: hand over to whatever is defined above this context,
|
|
229
|
+
# decided up front rather than by rescuing a NoMethodError, which
|
|
230
|
+
# could come from deeper in the stack (another receiver)
|
|
231
|
+
fallback = lambda do
|
|
232
|
+
return super(*args, **kwargs, &block) if StateMachines::State.fallback?(self, context, method_name)
|
|
233
|
+
|
|
234
|
+
raise state.invalid_context(self, method_name, args: args, kwargs: kwargs)
|
|
224
235
|
end
|
|
225
|
-
|
|
236
|
+
state.call(self, context_name, args: args, kwargs: kwargs, method_name: method_name, method_missing: fallback, &block)
|
|
237
|
+
end
|
|
238
|
+
context.send(visibility, method_name) if visibility
|
|
226
239
|
end
|
|
227
240
|
|
|
228
241
|
true
|
|
@@ -230,38 +243,60 @@ module StateMachines
|
|
|
230
243
|
|
|
231
244
|
# The list of methods that have been defined in this state's context
|
|
232
245
|
def context_methods
|
|
233
|
-
|
|
234
|
-
|
|
246
|
+
# Private ones too: they are as state-specific as public ones, and an
|
|
247
|
+
# unwrapped private method would run its state body in every state
|
|
248
|
+
(@context.instance_methods + @context.private_instance_methods).to_h do |name|
|
|
249
|
+
[name.to_sym, @context.instance_method(name)]
|
|
235
250
|
end
|
|
236
251
|
end
|
|
237
252
|
|
|
238
253
|
# Calls a method defined in this state's context on the given object. All
|
|
239
254
|
# arguments and any block will be passed into the method defined.
|
|
240
255
|
#
|
|
241
|
-
# If the
|
|
242
|
-
#
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
"State #{state.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{options[:method_name]}")
|
|
261
|
-
end
|
|
256
|
+
# If the object is not in this state and no other definition handles the
|
|
257
|
+
# call, StateMachines::InvalidContext (a NoMethodError) is raised.
|
|
258
|
+
#
|
|
259
|
+
# The method's own arguments come in +args+ and +kwargs+, kept apart from
|
|
260
|
+
# the dispatch options so that no argument of the method can be mistaken
|
|
261
|
+
# for one:
|
|
262
|
+
# * <tt>:method_missing</tt> - Called instead when the object is not in this
|
|
263
|
+
# state (e.g. to dispatch to the superclass); its errors propagate as
|
|
264
|
+
# they are. Without one, the call raises InvalidContext.
|
|
265
|
+
# * <tt>:method_name</tt> - The name reported when no state handles the call
|
|
266
|
+
def call(object, method, args: [], kwargs: {}, method_missing: nil, method_name: method, &)
|
|
267
|
+
# include_all: the aliased context method keeps a protected original's
|
|
268
|
+
# visibility, and respond_to? alone would not see it
|
|
269
|
+
if machine.states.match!(object) == self && object.respond_to?(method, true)
|
|
270
|
+
object.send(method, *args, **kwargs, &)
|
|
271
|
+
elsif method_missing
|
|
272
|
+
method_missing.call
|
|
273
|
+
else
|
|
274
|
+
raise invalid_context(object, method_name, args: args, kwargs: kwargs)
|
|
262
275
|
end
|
|
263
276
|
end
|
|
264
277
|
|
|
278
|
+
# The InvalidContext for calling +method_name+ on +object+ outside this
|
|
279
|
+
# state. Its args are what NoMethodError#args would hold: the positional
|
|
280
|
+
# arguments, then the keywords as a Hash when any were given.
|
|
281
|
+
def invalid_context(object, method_name, args: [], kwargs: {}) # :nodoc:
|
|
282
|
+
current = machine.states.match!(object)
|
|
283
|
+
InvalidContext.new(object,
|
|
284
|
+
"State #{current.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{method_name}",
|
|
285
|
+
method_name, kwargs.empty? ? args : [*args, kwargs])
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
# Whether a call to +method_name+ that leaves +context+ (a state context
|
|
289
|
+
# module) has somewhere to go: a definition above that context in the
|
|
290
|
+
# object's lookup chain (another state's context, an ancestor, a
|
|
291
|
+
# singleton extension), or a method_missing that claims it through
|
|
292
|
+
# respond_to_missing?.
|
|
293
|
+
def self.fallback?(object, context, method_name) # :nodoc:
|
|
294
|
+
# Kernel#method, in case the object overrides #method (e.g. a request)
|
|
295
|
+
method = Kernel.instance_method(:method).bind_call(object, method_name)
|
|
296
|
+
method = method.super_method until method.nil? || method.owner == context
|
|
297
|
+
!method&.super_method.nil? || object.send(:respond_to_missing?, method_name, true)
|
|
298
|
+
end
|
|
299
|
+
|
|
265
300
|
def draw(graph, options = {}, io = $stdout)
|
|
266
301
|
machine.renderer.draw_state(self, graph, options, io)
|
|
267
302
|
end
|
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
module StateMachines
|
|
4
4
|
# Represents a collection of states in a state machine
|
|
5
5
|
class StateCollection < NodeCollection
|
|
6
|
+
# Names are found by their string form too ('parked' / :parked). Values
|
|
7
|
+
# are not: a state matches a value by ==, so true must not find 'true'.
|
|
6
8
|
def initialize(machine) # :nodoc:
|
|
7
|
-
super(machine, index: %i[name qualified_name value])
|
|
9
|
+
super(machine, index: %i[name qualified_name value], string_keys: %i[name qualified_name])
|
|
8
10
|
end
|
|
9
11
|
|
|
10
12
|
# Determines whether the given object is in a specific state. If the
|
|
@@ -54,7 +56,13 @@ module StateMachines
|
|
|
54
56
|
# states.match(vehicle) # => nil
|
|
55
57
|
def match(object)
|
|
56
58
|
value = machine.read(object, :state)
|
|
57
|
-
self[value, :value]
|
|
59
|
+
indexed = self[value, :value]
|
|
60
|
+
# An index hit is eql?, so it matches by == unless the state has a custom
|
|
61
|
+
# :if matcher, which has the last word. Each matcher runs at most once:
|
|
62
|
+
# the scan skips the candidate already asked.
|
|
63
|
+
return indexed if indexed && (!indexed.matcher || indexed.matches?(value))
|
|
64
|
+
|
|
65
|
+
detect { |state| !state.equal?(indexed) && state.matches?(value) }
|
|
58
66
|
end
|
|
59
67
|
|
|
60
68
|
# Determines the current state of the given object as configured by this
|
|
@@ -64,6 +64,7 @@ module StateMachines
|
|
|
64
64
|
|
|
65
65
|
# Creates a new context for the given state
|
|
66
66
|
def initialize(state)
|
|
67
|
+
super()
|
|
67
68
|
@state = state
|
|
68
69
|
@machine = state.machine
|
|
69
70
|
|
|
@@ -86,10 +87,15 @@ module StateMachines
|
|
|
86
87
|
# end
|
|
87
88
|
# end
|
|
88
89
|
#
|
|
90
|
+
# Branch callbacks (<tt>:before</tt>, <tt>:around</tt>, <tt>:after</tt>)
|
|
91
|
+
# work as in StateMachines::Event#transition, e.g.
|
|
92
|
+
# <tt>transition to: :idling, on: :ignite, after: :log_ignition</tt>.
|
|
93
|
+
#
|
|
89
94
|
# See StateMachines::Machine#transition for a description of the possible
|
|
90
95
|
# configurations for defining transitions.
|
|
91
96
|
def transition(options)
|
|
92
|
-
|
|
97
|
+
# :do is not valid, but is let through so Event#transition explains it
|
|
98
|
+
StateMachines::OptionsValidator.assert_valid_keys!(options.except(:do), :from, :to, :on, :if, :unless, :before, :around, :after)
|
|
93
99
|
raise ArgumentError, 'Must specify :on event' unless options[:on]
|
|
94
100
|
raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from]
|
|
95
101
|
|
|
@@ -23,18 +23,17 @@ module StateMachines
|
|
|
23
23
|
end
|
|
24
24
|
end
|
|
25
25
|
|
|
26
|
-
module_function def draw_event(event, _graph, options
|
|
27
|
-
io =
|
|
26
|
+
module_function def draw_event(event, _graph, options = {}, io = $stdout)
|
|
27
|
+
io = options[:io] || io
|
|
28
28
|
io.puts " Event: #{event.name}"
|
|
29
29
|
end
|
|
30
30
|
|
|
31
|
-
module_function def draw_branch(branch, _graph, _event,
|
|
32
|
-
io = io || options[:io] || $stdout
|
|
31
|
+
module_function def draw_branch(branch, _graph, _event, _valid_states = [], io = $stdout)
|
|
33
32
|
io.puts " Branch: #{branch.inspect}"
|
|
34
33
|
end
|
|
35
34
|
|
|
36
|
-
module_function def draw_state(state, _graph, options
|
|
37
|
-
io =
|
|
35
|
+
module_function def draw_state(state, _graph, options = {}, io = $stdout)
|
|
36
|
+
io = options[:io] || io
|
|
38
37
|
io.puts " State: #{state.name}"
|
|
39
38
|
end
|
|
40
39
|
|
|
@@ -51,6 +50,9 @@ module StateMachines
|
|
|
51
50
|
out << "#{draw_requirement(requirement[:from])} => #{draw_requirement(requirement[:to])}"
|
|
52
51
|
out << " IF #{branch.if_condition}" if branch.if_condition
|
|
53
52
|
out << " UNLESS #{branch.unless_condition}" if branch.unless_condition
|
|
53
|
+
branch.state_guards.each do |kind, conditions|
|
|
54
|
+
out << " #{kind.upcase} #{conditions.map { |name, state| "#{name}: #{state}" }.join(', ')}"
|
|
55
|
+
end
|
|
54
56
|
io.puts out
|
|
55
57
|
end
|
|
56
58
|
end
|
|
@@ -42,9 +42,9 @@ module StateMachines
|
|
|
42
42
|
module UniversalBackend
|
|
43
43
|
def validate!(code, filename)
|
|
44
44
|
code = code.b
|
|
45
|
-
code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n)
|
|
46
|
-
"
|
|
47
|
-
|
|
45
|
+
code.sub!(/\A(?:\xef\xbb\xbf)?(\s*\#.*$)*(\n)?/n) do
|
|
46
|
+
"#{::Regexp.last_match(0)}#{"\n" if ::Regexp.last_match(1) && !::Regexp.last_match(2)}BEGIN{throw tag, :ok}\n"
|
|
47
|
+
end
|
|
48
48
|
code = code.force_encoding(Encoding::UTF_8)
|
|
49
49
|
catch { |tag| eval(code, binding, filename, __LINE__ - 1) } == :ok
|
|
50
50
|
end
|