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.
@@ -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
@@ -597,11 +594,65 @@ module StateMachines
597
594
  @action_hook_defined || (!self_only && owner_class.state_machines.any? { |_name, machine| machine.action == action && machine != self && machine.action_hook?(true) })
598
595
  end
599
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
+
600
642
  protected
601
643
 
602
644
  # Runs additional initialization hooks. By default, this is a no-op.
603
645
  def after_initialize; end
604
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
+
605
656
  # Always yields
606
657
  def transaction(_object)
607
658
  yield
@@ -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
- # Nodes will not differentiate between the String and Symbol versions of the
8
- # values being indexed.
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
- # Adds the given key / node combination to an index, including the string
186
- # and symbol versions of the index
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 the string and symbol
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 the string and symbol
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)
@@ -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 state
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
- context.class_eval <<-END_EVAL, __FILE__, __LINE__ + 1
219
- alias_method :"#{context_name}", :#{method_name}
220
- def #{method_name}(*args, &block)
221
- state = self.class.state_machine(#{machine.name.inspect}).states.fetch(#{name.inspect})
222
- options = {:method_missing => lambda {super(*args, &block)}, :method_name => #{method_name.inspect}}
223
- state.call(self, :"#{context_name}", *(args + [options]), &block)
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
- END_EVAL
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
- @context.instance_methods.inject({}) do |methods, name|
234
- methods.merge(name.to_sym => @context.instance_method(name))
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 method has never been defined for this state, then a NoMethodError
242
- # will be raised.
243
- def call(object, method, *args, &)
244
- options = args.last.is_a?(Hash) ? args.pop : {}
245
- options = { method_name: method }.merge(options)
246
- state = machine.states.match!(object)
247
-
248
- if state == self && object.respond_to?(method)
249
- object.send(method, *args, &)
250
- elsif (method_missing = options[:method_missing])
251
- # Dispatch to the superclass since the object either isn't in this state
252
- # or this state doesn't handle the method
253
- begin
254
- method_missing.call
255
- rescue NoMethodError => e
256
- raise unless e.name.to_s == options[:method_name].to_s && e.args == args
257
-
258
- # No valid context for this method
259
- raise InvalidContext.new(object,
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] || detect { |state| state.matches?(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