state_machines-yard 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +12 -4
  3. data/.github/workflows/release.yml +8 -6
  4. data/.release-please-manifest.json +3 -0
  5. data/.rubocop.yml +38 -0
  6. data/CHANGELOG.md +54 -0
  7. data/Gemfile +12 -1
  8. data/README.md +45 -0
  9. data/Rakefile +21 -3
  10. data/lib/state_machines/yard/description.rb +77 -0
  11. data/lib/state_machines/yard/handlers/actions.rb +113 -0
  12. data/lib/state_machines/yard/handlers/base.rb +145 -20
  13. data/lib/state_machines/yard/handlers/callback.rb +56 -0
  14. data/lib/state_machines/yard/handlers/event.rb +16 -12
  15. data/lib/state_machines/yard/handlers/machine.rb +258 -253
  16. data/lib/state_machines/yard/handlers/requirements.rb +92 -0
  17. data/lib/state_machines/yard/handlers/state.rb +16 -12
  18. data/lib/state_machines/yard/handlers/transition.rb +59 -30
  19. data/lib/state_machines/yard/handlers.rb +3 -1
  20. data/lib/state_machines/yard/renderer.rb +62 -0
  21. data/lib/state_machines/yard/templates/default/class/html/setup.rb +14 -7
  22. data/lib/state_machines/yard/templates/default/class/html/state_machines.erb +33 -0
  23. data/lib/state_machines/yard/templates.rb +2 -0
  24. data/lib/state_machines/yard/version.rb +3 -1
  25. data/lib/state_machines/yard.rb +7 -0
  26. data/release-please-config.json +11 -0
  27. data/state_machines-yard.gemspec +16 -8
  28. data/test/description_test.rb +138 -0
  29. data/test/handlers/base_test.rb +43 -18
  30. data/test/handlers/callback_test.rb +168 -0
  31. data/test/handlers/event_test.rb +32 -19
  32. data/test/handlers/guards_test.rb +180 -0
  33. data/test/handlers/machine_test.rb +100 -16
  34. data/test/handlers/review_test.rb +192 -0
  35. data/test/handlers/state_test.rb +20 -13
  36. data/test/handlers/transition_test.rb +154 -19
  37. data/test/integration_test.rb +47 -36
  38. data/test/templates_test.rb +39 -16
  39. data/test/test_helper.rb +24 -10
  40. metadata +103 -20
@@ -1,3 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative '../renderer'
4
+
1
5
  module StateMachines
2
6
  module Yard
3
7
  module Handlers
@@ -5,79 +9,129 @@ module StateMachines
5
9
  class Machine < Base
6
10
  handles method_call(:state_machine)
7
11
  namespace_only
8
-
12
+
9
13
  # Store the handled method name for testing
10
14
  @handles_method = :state_machine
11
15
 
16
+ # What a renderer adds to a machine's entry
17
+ DIAGRAM_KEYS = %i[image mermaid renderer].freeze
18
+
19
+ # Stands for an initial state the documented code computes
20
+ DYNAMIC_INITIAL_STATE = ->(_object) {}
21
+
12
22
  # The generated state machine
13
23
  attr_reader :machine
14
24
 
15
25
  def process
16
- # Cross-file storage for state machines
17
- globals.state_machines ||= Hash.new { |h, k| h[k] = {} }
18
- namespace['state_machines'] ||= {}
19
-
20
- # Create new machine
21
- klass = inherited_machine ? Class.new(inherited_machine.owner_class) : Class.new { extend StateMachines::MacroMethods }
22
- @machine = klass.state_machine(name, options) {}
26
+ name # A machine whose name is code is not documented
27
+
28
+ # A machine the class already documents is reopened, as the core
29
+ # does. Given a block, even an empty one, the core copies an
30
+ # inherited machine for the subclass instead of extending the
31
+ # superclass's, and applies the subclass's options to the copy.
32
+ @machine = (reopened_machine&.owner_class || owner_class).state_machine(name, options) do
33
+ # The statement's block is parsed below
34
+ end
23
35
 
24
- # Track the state machine
25
- globals.state_machines[namespace.name][name] = machine
26
- namespace['state_machines'][name] = {name: name, description: statement.docstring}
36
+ track_machine
27
37
 
28
38
  # Parse the block
29
- parse_block(statement.last.last, owner: machine)
39
+ parse_block(statement.block.last, owner: machine) if statement.block
30
40
 
31
- # Draw the machine for reference in the template
32
- file = Tempfile.new(['state_machine', '.png'])
33
- begin
34
- if machine.draw(name: File.basename(file.path, '.png'), path: File.dirname(file.path), orientation: 'landscape')
35
- namespace['state_machines'][name][:image] = file.read
36
- end
37
- ensure
38
- # Clean up tempfile
39
- file.close
40
- file.unlink
41
- end
41
+ document_events
42
+ document_diagram
42
43
 
43
44
  # Define auto-generated methods
44
45
  define_macro_methods
45
46
  define_state_methods
46
47
  define_event_methods
48
+ rescue Unreadable, ArgumentError => e
49
+ # A machine the core refuses (an option a reopened machine cannot
50
+ # change) is not documented as something else
51
+ skip('state machine', e)
47
52
  end
48
53
 
49
54
  protected
50
- # Extracts the machine name's
55
+
56
+ # The class the documented machine is built on: a subclass of the
57
+ # inherited machine's owner, so the machine extends that one. It is
58
+ # named as the documented class, which diagrams show in their title.
59
+ def owner_class
60
+ klass = inherited_machine ? Class.new(inherited_machine.owner_class) : Class.new { extend MacroMethods }
61
+ path = namespace.path
62
+ klass.define_singleton_method(:name) { path }
63
+ klass.define_singleton_method(:to_s) { path }
64
+ klass
65
+ end
66
+
67
+ # The machine this class already documents under the name, if any
68
+ def reopened_machine
69
+ globals.state_machines&.dig(namespace.path, name)
70
+ end
71
+
72
+ # Stores the machine across files (subclasses find it there) and on
73
+ # the documented class
74
+ def track_machine
75
+ globals.state_machines ||= Hash.new { |h, k| h[k] = {} }
76
+ globals.state_machines[namespace.path][name] = machine
77
+ namespace['state_machines'] ||= {}
78
+ entry = namespace['state_machines'][name] ||= { name: name }
79
+ entry[:description] = statement.docstring unless statement.docstring.to_s.empty? && entry[:description]
80
+ end
81
+
82
+ # The events' transitions, guards and callbacks as text, whatever
83
+ # renderer draws the diagram
84
+ def document_events
85
+ @events = Description.events(machine).to_h { [it[:name], it] }
86
+ namespace['state_machines'][name][:events] = @events.values
87
+ end
88
+
89
+ # The machine's diagram, drawn by the selected renderer
90
+ # A reopened machine is drawn again: its previous diagram shows only
91
+ # what was declared before, so it is never kept in place of a new one
92
+ def document_diagram
93
+ entry = namespace['state_machines'][name]
94
+ stale = entry.slice(*DIAGRAM_KEYS)
95
+ DIAGRAM_KEYS.each { entry.delete(it) }
96
+ render = Renderer.render(machine)
97
+ return entry.merge!(render, renderer: Renderer.selection) if render
98
+
99
+ warn_stale_diagram unless stale.except(:renderer).empty?
100
+ end
101
+
102
+ def warn_stale_diagram
103
+ log.warn "state_machines-yard: the reopened #{name} machine could not be drawn again; " \
104
+ "its earlier diagram is left out (#{parser.file}:#{statement.line})"
105
+ end
106
+
107
+ # The machine's name: its first argument, :state when there is none
51
108
  def name
52
109
  @name ||= begin
53
- ast = statement.parameters.first
54
- if ast && [:symbol_literal, :string_literal].include?(ast.type)
55
- extract_node_name(ast)
56
- else
57
- :state
58
- end
110
+ argument = positional_arguments.first
111
+ argument ? name_literal(argument) : :state
59
112
  end
60
113
  end
61
114
 
62
- # Extracts the machine options. Note that this will only extract a
63
- # subset of the options supported.
115
+ # The machine options documentation depends on. Note that this will
116
+ # only extract a subset of the options supported. An initial state
117
+ # written as code is decided when the object is created, so no state
118
+ # is documented as the initial one.
64
119
  def options
65
120
  @options ||= begin
66
- options = {}
67
- ast = statement.parameters(false).last
68
-
69
- if !inherited_machine && ast && ![:symbol_literal, :string_literal].include?(ast.type)
70
- ast.children.each do |assoc|
71
- # Only extract important options
72
- key = extract_node_name(assoc[0])
73
- next unless [:initial, :attribute, :namespace, :action].include?(key)
121
+ options = literal_options(%i[initial attribute namespace action])
122
+ options[:initial] = DYNAMIC_INITIAL_STATE if dynamic_initial_state?
123
+ options
124
+ end
125
+ end
74
126
 
75
- value = extract_node_name(assoc[1])
76
- options[key] = value
77
- end
127
+ def dynamic_initial_state?
128
+ option_pairs.any? do |key, value|
129
+ literal(key) == :initial && begin
130
+ literal(value)
131
+ false
132
+ rescue Unreadable
133
+ true
78
134
  end
79
-
80
- options
81
135
  end
82
136
  end
83
137
 
@@ -86,17 +140,15 @@ module StateMachines
86
140
  def inherited_machine
87
141
  @inherited_machine ||= begin
88
142
  namespace.inheritance_tree.each do |ancestor|
89
- begin
90
- ensure_loaded!(ancestor)
91
- rescue YARD::Handlers::NamespaceMissingError
92
- # Ignore: just means that we can't access an ancestor
93
- end
143
+ ensure_loaded!(ancestor)
144
+ rescue YARD::Handlers::NamespaceMissingError
145
+ # Ignore: just means that we can't access an ancestor
94
146
  end
95
147
 
96
148
  # Find the first ancestor that has the machine
97
149
  loaded_superclasses.find do |superclass|
98
150
  if superclass != namespace
99
- machine = globals.state_machines[superclass.name][name]
151
+ machine = globals.state_machines[superclass.path][name]
100
152
  break machine if machine
101
153
  end
102
154
  end
@@ -106,7 +158,7 @@ module StateMachines
106
158
  # Gets members of this class's superclasses have already been loaded
107
159
  # by YARD
108
160
  def loaded_superclasses
109
- namespace.inheritance_tree.select { |ancestor| ancestor.is_a?(YARD::CodeObjects::ClassObject) }
161
+ namespace.inheritance_tree.grep(YARD::CodeObjects::ClassObject)
110
162
  end
111
163
 
112
164
  # Gets a list of all attributes for the current class, including those
@@ -120,12 +172,16 @@ module StateMachines
120
172
  # Gets the type of ORM integration being used based on the list of
121
173
  # ancestors (including mixins)
122
174
  def integration
123
- @integration ||= Integrations.match_ancestors(namespace.inheritance_tree(true).map { |ancestor| ancestor.path })
175
+ @integration ||= Integrations.match_ancestors(namespace.inheritance_tree(true).map(&:path))
124
176
  end
125
177
 
126
178
  # Gets the class type being used to define states. Default is "Symbol".
127
179
  def state_type
128
- @state_type ||= machine.states.any? ? machine.states.map { |state| state.name }.compact.first.class.to_s : 'Symbol'
180
+ @state_type ||= if machine.states.any?
181
+ machine.states.filter_map(&:name).first.class.to_s
182
+ else
183
+ 'Symbol'
184
+ end
129
185
  end
130
186
 
131
187
  # Gets the class type being used to define events. Default is "Symbol".
@@ -133,224 +189,173 @@ module StateMachines
133
189
  @event_type ||= machine.events.any? ? machine.events.first.name.class.to_s : 'Symbol'
134
190
  end
135
191
 
136
- # Defines auto-generated macro methods for the given machine
192
+ # Registers a method the machine generates, with its documentation
193
+ def document_method(name, docstring, parameters: nil, scope: :instance)
194
+ method = YARD::CodeObjects::MethodObject.new(namespace, name, scope)
195
+ register(method)
196
+ # YARD checks @param tags against the parameters, as [name, default]
197
+ # pairs, when the docstring is set
198
+ method.parameters = parameters.map { |name, default| [name, default] } if parameters
199
+ method.docstring = docstring
200
+ method
201
+ end
202
+
203
+ # Registers an attribute's reader and writer
204
+ def document_attribute(attribute, description)
205
+ namespace.attributes[:instance][attribute] = {
206
+ read: document_method(attribute, ["Gets the current #{description} for the machine",
207
+ "@return The #{description}"]),
208
+ write: document_method("#{attribute}=", ['Sets the current value for the machine',
209
+ "@param new_#{attribute} The new value to set"],
210
+ parameters: ["new_#{attribute}"])
211
+ }
212
+ end
213
+
214
+ # Defines auto-generated macro methods for the given machine. A
215
+ # subclass's machine extends its superclass's, so the methods that
216
+ # read the current state are documented on it too; the attributes and
217
+ # the methods that list or fire events are the superclass's.
137
218
  def define_macro_methods
138
- # Don't exit early for inherited machine since we need to register instance methods
139
- # even for inherited machines
140
-
141
- # Human state name lookup (class method)
142
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "human_#{machine.attribute(:name)}", :class))
143
- m.docstring = [
144
- 'Gets the humanized name for the given state.',
145
- "@param [#{state_type}] state The state to look up",
146
- '@return [String] The human state name'
147
- ]
148
- m.parameters = ['state']
149
-
150
- # Human event name lookup (class method)
151
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "human_#{machine.attribute(:event_name)}", :class))
152
- m.docstring = [
153
- 'Gets the humanized name for the given event.',
154
- "@param [#{event_type}] event The event to look up",
155
- '@return [String] The human event name'
156
- ]
157
- m.parameters = ['event']
158
-
159
- # Skip the rest if this is an inherited machine
219
+ define_human_name_methods
220
+ define_state_reader_methods
160
221
  return if inherited_machine
161
222
 
162
- # Only register attributes when the accessor isn't explicitly defined
163
- # by the class / superclass *and* isn't defined by inference from the
164
- # ORM being used
223
+ define_attribute_methods
224
+ define_event_list_methods
225
+ end
226
+
227
+ def define_human_name_methods
228
+ document_method("human_#{machine.attribute(:name)}",
229
+ ['Gets the humanized name for the given state.',
230
+ "@param [#{state_type}] state The state to look up",
231
+ '@return [String] The human state name'],
232
+ parameters: ['state'], scope: :class)
233
+ document_method("human_#{machine.attribute(:event_name)}",
234
+ ['Gets the humanized name for the given event.',
235
+ "@param [#{event_type}] event The event to look up",
236
+ '@return [String] The human event name'],
237
+ parameters: ['event'], scope: :class)
238
+ end
239
+
240
+ def define_state_reader_methods
241
+ document_method("#{machine.name}?",
242
+ ['Checks the given state name against the current state.',
243
+ "@param [#{state_type}] state_name The name of the state to check",
244
+ '@return [Boolean] True if they are the same state, otherwise false',
245
+ '@raise [IndexError] If the state name is invalid'],
246
+ parameters: ['state_name'])
247
+ document_method(machine.attribute(:name),
248
+ ['Gets the internal name of the state for the current value.',
249
+ "@return [#{state_type}] The internal name of the state"])
250
+ document_method("human_#{machine.attribute(:name)}",
251
+ ['Gets the human-readable name of the state for the current value.',
252
+ '@return [String] The human-readable state name'])
253
+ end
254
+
255
+ # Only register attributes when the accessor isn't explicitly defined
256
+ # by the class / superclass *and* isn't defined by inference from the
257
+ # ORM being used
258
+ def define_attribute_methods
165
259
  unless integration || instance_attributes.include?(machine.attribute.to_sym)
166
- attribute = machine.attribute
167
- namespace.attributes[:instance][attribute] = {}
168
-
169
- # Machine attribute getter
170
- register(m = YARD::CodeObjects::MethodObject.new(namespace, attribute))
171
- namespace.attributes[:instance][attribute][:read] = m
172
- m.docstring = [
173
- 'Gets the current attribute value for the machine',
174
- '@return The attribute value'
175
- ]
176
-
177
- # Machine attribute setter
178
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "#{attribute}="))
179
- namespace.attributes[:instance][attribute][:write] = m
180
- m.docstring = [
181
- 'Sets the current value for the machine',
182
- "@param new_#{attribute} The new value to set"
183
- ]
184
- m.parameters = ["new_#{attribute}"]
260
+ document_attribute(machine.attribute, 'attribute value')
185
261
  end
262
+ document_attribute("#{machine.name}_event", 'event attribute value') if action?
263
+ end
186
264
 
187
- if integration && integration.defaults[:action] && !options.include?(:action) || options[:action]
188
- attribute = "#{machine.name}_event"
189
- namespace.attributes[:instance][attribute] = {}
190
-
191
- # Machine event attribute getter
192
- register(m = YARD::CodeObjects::MethodObject.new(namespace, attribute))
193
- namespace.attributes[:instance][attribute][:read] = m
194
- m.docstring = [
195
- 'Gets the current event attribute value for the machine',
196
- '@return The event attribute value'
197
- ]
198
-
199
- # Machine event attribute setter
200
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "#{attribute}="))
201
- namespace.attributes[:instance][attribute][:write] = m
202
- m.docstring = [
203
- 'Sets the current value for the machine',
204
- "@param new_#{attribute} The new value to set"
205
- ]
206
- m.parameters = ["new_#{attribute}"]
207
- end
265
+ # Whether the machine has an action, its own or its integration's
266
+ def action?
267
+ options.include?(:action) ? options[:action] : integration&.defaults&.[](:action)
268
+ end
208
269
 
209
- # These instance methods are always defined, even for inherited machines
210
-
211
- # Presence query
212
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "#{machine.name}?"))
213
- m.docstring = [
214
- 'Checks the given state name against the current state.',
215
- "@param [#{state_type}] state_name The name of the state to check",
216
- '@return [Boolean] True if they are the same state, otherwise false',
217
- '@raise [IndexError] If the state name is invalid'
218
- ]
219
- m.parameters = ['state_name']
220
-
221
- # Internal state name
222
- register(m = YARD::CodeObjects::MethodObject.new(namespace, machine.attribute(:name)))
223
- m.docstring = [
224
- 'Gets the internal name of the state for the current value.',
225
- "@return [#{state_type}] The internal name of the state"
226
- ]
227
-
228
- # Human state name instance method - this is always defined regardless of inheritance
229
- # Ensure the name is correct - we explicitly check the attribute name to make sure it's generated correctly
230
- human_method_name = "human_#{machine.attribute(:name)}"
231
- register(m = YARD::CodeObjects::MethodObject.new(namespace, human_method_name))
232
- m.docstring = [
233
- 'Gets the human-readable name of the state for the current value.',
234
- '@return [String] The human-readable state name'
235
- ]
236
-
237
- # Debug output for testing - we want to make sure we're registering the method correctly
238
- # puts "Registered instance method: #{namespace}##{human_method_name} (#{m})"
239
-
240
- # The below methods should only be defined for non-inherited machines
241
- return if inherited_machine
270
+ def define_event_list_methods
271
+ requirements = ['@param [Hash] requirements The transition requirements to test against']
272
+ guard = '@option requirements [Boolean] :guard Whether to guard transitions with conditionals'
273
+ from_to_on = ["@option requirements [#{state_type}] :from (the current state) One or more initial states",
274
+ "@option requirements [#{state_type}] :to One or more target states",
275
+ "@option requirements [#{event_type}] :on One or more events that fire the transition"]
276
+
277
+ document_method(machine.attribute(:events),
278
+ ["Gets the list of events that can be fired on the current #{machine.name} " \
279
+ '(uses the *unqualified* event names)', *requirements, *from_to_on, guard,
280
+ "@return [Array<#{event_type}>] The list of event names"],
281
+ parameters: [%w[requirements {}]])
282
+ document_method(machine.attribute(:transitions),
283
+ ["Gets the list of transitions that can be made for the current #{machine.name}",
284
+ *requirements, *from_to_on, guard,
285
+ '@return [Array<StateMachines::Transition>] The available transitions'],
286
+ parameters: [%w[requirements {}]])
287
+ define_path_and_fire_methods(requirements, guard)
288
+ end
242
289
 
243
- # Available events
244
- register(m = YARD::CodeObjects::MethodObject.new(namespace, machine.attribute(:events)))
245
- m.docstring = [
246
- "Gets the list of events that can be fired on the current #{machine.name} (uses the *unqualified* event names)",
247
- '@param [Hash] requirements The transition requirements to test against',
248
- "@option requirements [#{state_type}] :from (the current state) One or more initial states",
249
- "@option requirements [#{state_type}] :to One or more target states",
250
- "@option requirements [#{event_type}] :on One or more events that fire the transition",
251
- '@option requirements [Boolean] :guard Whether to guard transitions with conditionals',
252
- "@return [Array<#{event_type}>] The list of event names"
253
- ]
254
- m.parameters = [['requirements', '{}']]
255
-
256
- # Available transitions
257
- register(m = YARD::CodeObjects::MethodObject.new(namespace, machine.attribute(:transitions)))
258
- m.docstring = [
259
- "Gets the list of transitions that can be made for the current #{machine.name}",
260
- '@param [Hash] requirements The transition requirements to test against',
261
- "@option requirements [#{state_type}] :from (the current state) One or more initial states",
262
- "@option requirements [#{state_type}] :to One or more target states",
263
- "@option requirements [#{event_type}] :on One or more events that fire the transition",
264
- '@option requirements [Boolean] :guard Whether to guard transitions with conditionals',
265
- '@return [Array<StateMachines::Transition>] The available transitions'
266
- ]
267
- m.parameters = [['requirements', '{}']]
268
-
269
- # Available transition paths
270
- register(m = YARD::CodeObjects::MethodObject.new(namespace, machine.attribute(:paths)))
271
- m.docstring = [
272
- "Gets the list of sequences of transitions that can be run for the current #{machine.name}",
273
- '@param [Hash] requirements The transition requirements to test against',
274
- "@option requirements [#{state_type}] :from (the current state) The initial state",
275
- "@option requirements [#{state_type}] :to The target state",
276
- '@option requirements [Boolean] :deep Whether to enable deep searches for the target state',
277
- '@option requirements [Boolean] :guard Whether to guard transitions with conditionals',
278
- '@return [StateMachines::PathCollection] The collection of paths'
279
- ]
280
- m.parameters = [['requirements', '{}']]
281
-
282
- # Generic event fire
283
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "fire_#{machine.attribute(:event)}"))
284
- m.docstring = [
285
- "Fires an arbitrary #{machine.name} event with the given argument list",
286
- "@param [#{event_type}] event The name of the event to fire",
287
- '@param args Optional arguments to include in the transition',
288
- '@return [Boolean] +true+ if the event succeeds, otherwise +false+'
289
- ]
290
- m.parameters = ['event', '*args']
290
+ def define_path_and_fire_methods(requirements, guard)
291
+ document_method(machine.attribute(:paths),
292
+ ["Gets the list of sequences of transitions that can be run for the current #{machine.name}",
293
+ *requirements,
294
+ "@option requirements [#{state_type}] :from (the current state) The initial state",
295
+ "@option requirements [#{state_type}] :to The target state",
296
+ '@option requirements [Boolean] :deep Whether to enable deep searches for the target state',
297
+ guard, '@return [StateMachines::PathCollection] The collection of paths'],
298
+ parameters: [%w[requirements {}]])
299
+ document_method("fire_#{machine.attribute(:event)}",
300
+ ["Fires an arbitrary #{machine.name} event with the given argument list",
301
+ "@param [#{event_type}] event The name of the event to fire",
302
+ '@param args Optional arguments to include in the transition',
303
+ '@return [Boolean] +true+ if the event succeeds, otherwise +false+'],
304
+ parameters: ['event', '*args'])
291
305
  end
292
306
 
293
307
  # Defines auto-generated event methods for the given machine
294
308
  def define_event_methods
295
309
  machine.events.each do |event|
296
- next if inherited_machine && inherited_machine.events[event.name]
297
-
298
- # Event query
299
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "can_#{event.qualified_name}?"))
300
- m.docstring = [
301
- "Checks whether #{event.name.inspect} can be fired.",
302
- '@param [Hash] requirements The transition requirements to test against',
303
- "@option requirements [#{state_type}] :from One or more initial states",
304
- "@option requirements [#{state_type}] :to One or more target states",
305
- '@option requirements [Boolean] :guard Whether to guard transitions with conditionals',
306
- "@return [Boolean] +true+ if #{event.name.inspect} can be fired, otherwise +false+"
307
- ]
308
- m.parameters = [['requirements', '{}']]
309
-
310
- # Event transition
311
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "#{event.qualified_name}_transition"))
312
- m.docstring = [
313
- "Gets the next transition that would be performed if #{event.name.inspect} were to be fired.",
314
- '@param [Hash] requirements The transition requirements to test against',
315
- "@option requirements [#{state_type}] :from One or more initial states",
316
- "@option requirements [#{state_type}] :to One or more target states",
317
- '@option requirements [Boolean] :guard Whether to guard transitions with conditionals',
318
- '@return [StateMachines::Transition] The transition that would be performed or +nil+'
319
- ]
320
- m.parameters = [['requirements', '{}']]
321
-
322
- # Fire event
323
- register(m = YARD::CodeObjects::MethodObject.new(namespace, event.qualified_name))
324
- m.docstring = [
325
- "Fires the #{event.name.inspect} event.",
326
- '@param [Array] args Optional arguments to include in transition callbacks',
327
- '@return [Boolean] +true+ if the transition succeeds, otherwise +false+'
328
- ]
329
- m.parameters = ['*args']
330
-
331
- # Fire event (raises exception)
332
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "#{event.qualified_name}!"))
333
- m.docstring = [
334
- "Fires the #{event.name.inspect} event, raising an exception if it fails.",
335
- '@param [Array] args Optional arguments to include in transition callbacks',
336
- '@return [Boolean] +true+ if the transition succeeds',
337
- '@raise [StateMachines::InvalidTransition] If the transition fails'
338
- ]
339
- m.parameters = ['*args']
310
+ next if inherited_machine&.events&.[](event.name)
311
+
312
+ define_event_query_methods(event)
313
+ define_event_fire_methods(event)
340
314
  end
341
315
  end
342
316
 
317
+ def define_event_query_methods(event)
318
+ requirements = ['@param [Hash] requirements The transition requirements to test against',
319
+ "@option requirements [#{state_type}] :from One or more initial states",
320
+ "@option requirements [#{state_type}] :to One or more target states",
321
+ '@option requirements [Boolean] :guard Whether to guard transitions with conditionals']
322
+
323
+ document_method("can_#{event.qualified_name}?",
324
+ ["Checks whether #{event.name.inspect} can be fired.", *requirements,
325
+ "@return [Boolean] +true+ if #{event.name.inspect} can be fired, otherwise +false+"],
326
+ parameters: [%w[requirements {}]])
327
+ document_method("#{event.qualified_name}_transition",
328
+ ["Gets the next transition that would be performed if #{event.name.inspect} " \
329
+ 'were to be fired.', *requirements,
330
+ '@return [StateMachines::Transition] The transition that would be performed or +nil+'],
331
+ parameters: [%w[requirements {}]])
332
+ end
333
+
334
+ def define_event_fire_methods(event)
335
+ args = '@param [Array] args Optional arguments to include in transition callbacks'
336
+
337
+ description = Description.docstring_lines(@events.fetch(event.name.to_s))
338
+
339
+ document_method(event.qualified_name,
340
+ ["Fires the #{event.name.inspect} event.", *description, args,
341
+ '@return [Boolean] +true+ if the transition succeeds, otherwise +false+'],
342
+ parameters: ['*args'])
343
+ document_method("#{event.qualified_name}!",
344
+ ["Fires the #{event.name.inspect} event, raising an exception if it fails.", *description,
345
+ args,
346
+ '@return [Boolean] +true+ if the transition succeeds',
347
+ '@raise [StateMachines::InvalidTransition] If the transition fails'],
348
+ parameters: ['*args'])
349
+ end
350
+
343
351
  # Defines auto-generated state methods for the given machine
344
352
  def define_state_methods
345
353
  machine.states.each do |state|
346
- next if inherited_machine && inherited_machine.states[state.name] || !state.name
347
-
348
- # State query
349
- register(m = YARD::CodeObjects::MethodObject.new(namespace, "#{state.qualified_name}?"))
350
- m.docstring = [
351
- "Checks whether #{state.name.inspect} is the current state.",
352
- '@return [Boolean] +true+ if this is the current state, otherwise +false+'
353
- ]
354
+ next if inherited_machine&.states&.[](state.name) || !state.name
355
+
356
+ document_method("#{state.qualified_name}?",
357
+ ["Checks whether #{state.name.inspect} is the current state.",
358
+ '@return [Boolean] +true+ if this is the current state, otherwise +false+'])
354
359
  end
355
360
  end
356
361
  end