state_machines-yard 0.0.1 → 0.3.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 +5 -5
  2. data/.github/workflows/ci.yml +32 -0
  3. data/.github/workflows/release.yml +18 -0
  4. data/.release-please-manifest.json +3 -0
  5. data/.rubocop.yml +38 -0
  6. data/CHANGELOG.md +44 -0
  7. data/Gemfile +13 -0
  8. data/LICENSE.txt +1 -1
  9. data/README.md +50 -1
  10. data/Rakefile +29 -0
  11. data/lib/state_machines/yard/description.rb +74 -0
  12. data/lib/state_machines/yard/handlers/base.rb +122 -21
  13. data/lib/state_machines/yard/handlers/callback.rb +96 -0
  14. data/lib/state_machines/yard/handlers/event.rb +20 -11
  15. data/lib/state_machines/yard/handlers/machine.rb +263 -241
  16. data/lib/state_machines/yard/handlers/requirements.rb +92 -0
  17. data/lib/state_machines/yard/handlers/state.rb +20 -11
  18. data/lib/state_machines/yard/handlers/transition.rb +26 -31
  19. data/lib/state_machines/yard/handlers.rb +4 -6
  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 +15 -4
  26. data/release-please-config.json +11 -0
  27. data/state_machines-yard.gemspec +19 -11
  28. data/test/description_test.rb +99 -0
  29. data/test/handlers/base_test.rb +83 -0
  30. data/test/handlers/callback_test.rb +137 -0
  31. data/test/handlers/event_test.rb +97 -0
  32. data/test/handlers/guards_test.rb +180 -0
  33. data/test/handlers/machine_test.rb +156 -0
  34. data/test/handlers/review_test.rb +192 -0
  35. data/test/handlers/state_test.rb +73 -0
  36. data/test/handlers/transition_test.rb +142 -0
  37. data/test/integration_test.rb +163 -0
  38. data/test/templates_test.rb +95 -0
  39. data/test/test_helper.rb +51 -0
  40. metadata +146 -16
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: ae4aeccc3211632b5b25f19bfa30b576adfcc4fc
4
- data.tar.gz: 797a207f6c1a883619c089148ab7d76fa4c5640c
2
+ SHA256:
3
+ metadata.gz: 2b674c24b722f0643ed70d4c459d9d62200f4b821035280ed970e67509da382d
4
+ data.tar.gz: e2157b72de56685420efcb67624dc25404fd162f6b685a3ba2e78f9896c924c4
5
5
  SHA512:
6
- metadata.gz: 3bd4c0b651acab5ea3469ec81e33a78209ebbec1f81c84adc89159fa42cba8b97178570d662223388855c7cbe8493c65a84c9cc0d9ffcdedbcd4d063939065d2
7
- data.tar.gz: f027b5799f58e0a5a43d1910013ee1d55d8d0eb0af5ae75ea57c39b7e90e5ba19139c6f486bb5b092841ebabae7b811d31344dc32fdd2e4cba840288b5fba72b
6
+ metadata.gz: f0fe6c896583ddd924e70ddc0b29f52b9dcb122909044ca978440edbc3e72ecce330c0896b08f4976835268824f8deb37a9ab1134c94cd2b06dd6db4558b8772
7
+ data.tar.gz: 89461e5685c9892896d531e4b9f91dcc1a876da0604cd3a45ac291cfffe6106b8d238722026f385e7aff1437a0368aa3433f689a5b54c4eae52c57faf5dec9db
@@ -0,0 +1,32 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [ master ]
6
+ pull_request:
7
+ branches: [ master ]
8
+
9
+ jobs:
10
+ build:
11
+
12
+ runs-on: ubuntu-latest
13
+ strategy:
14
+ fail-fast: false
15
+ matrix:
16
+ ruby-version: ['4.0']
17
+ renderer: ['none', 'graphviz', 'mermaid']
18
+
19
+ steps:
20
+ - uses: actions/checkout@v7
21
+ - name: Set up Ruby
22
+ uses: ruby/setup-ruby@v1
23
+ with:
24
+ ruby-version: ${{ matrix.ruby-version }}
25
+ bundler-cache: true
26
+ # Every job draws a GraphViz diagram in the renderer tests
27
+ - name: Install graphviz
28
+ run: sudo apt-get update && sudo apt-get install -y graphviz
29
+ - name: Run tests
30
+ env:
31
+ STATE_MACHINES_RENDERER: ${{ matrix.renderer }}
32
+ run: bundle exec rake
@@ -0,0 +1,18 @@
1
+ name: release-please
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - master
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: write
11
+ pull-requests: write
12
+ issues: write
13
+
14
+ jobs:
15
+ release-please:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - uses: googleapis/release-please-action@v5
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "0.3.0"
3
+ }
data/.rubocop.yml ADDED
@@ -0,0 +1,38 @@
1
+ plugins:
2
+ - rubocop-minitest
3
+ - rubocop-rake
4
+ - rubocop-performance
5
+ AllCops:
6
+ TargetRubyVersion: 4.0
7
+ NewCops: enable
8
+ Exclude:
9
+ - 'pkg/**/*'
10
+ - 'tmp/**/*'
11
+ - 'vendor/**/*'
12
+
13
+ Style/Documentation:
14
+ Enabled: false
15
+
16
+ Metrics/MethodLength:
17
+ Max: 20
18
+ Exclude:
19
+ - 'test/**/*' # Tests hold their fixture source
20
+
21
+ Metrics/AbcSize:
22
+ Max: 40
23
+
24
+ Minitest/MultipleAssertions:
25
+ Enabled: false
26
+
27
+ Gemspec/DevelopmentDependencies:
28
+ Enabled: false
29
+
30
+ Metrics/ClassLength:
31
+ Exclude:
32
+ - 'test/**/*' # Allow longer test classes
33
+ - 'lib/state_machines/yard/handlers/machine.rb' # The generated methods' documentation
34
+
35
+ # Test classes are long blocks by nature.
36
+ Metrics/BlockLength:
37
+ Exclude:
38
+ - 'test/**/*'
data/CHANGELOG.md ADDED
@@ -0,0 +1,44 @@
1
+ # Changelog
2
+
3
+ ## [0.3.0](https://github.com/state-machines/state_machines-yard/compare/v0.2.0...v0.3.0) (2026-11-17)
4
+
5
+
6
+ ### Features
7
+
8
+ * document each event's transitions, guards and callbacks as text ([d79a9a1](https://github.com/state-machines/state_machines-yard/commit/d79a9a117b380183301659221bcc8664c451c021))
9
+ * document the guards and options the DSL declares ([75c2603](https://github.com/state-machines/state_machines-yard/commit/75c26039e59d00b61cfa12bf7524acdabfab3481))
10
+ * document transition callbacks ([3bb2645](https://github.com/state-machines/state_machines-yard/commit/3bb264539d585a49fadeaab663ba18b62bb06a04))
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * a code condition is never evaluated as a String condition ([47d25d6](https://github.com/state-machines/state_machines-yard/commit/47d25d688bdf80a6a61409a2d7eb1af84aa2d828))
16
+ * a documented machine is owned by a class named as the documented one ([82e8e5c](https://github.com/state-machines/state_machines-yard/commit/82e8e5ca9a6695adaf33a0dbb34e1e49b0ec881a))
17
+ * a reopened machine never publishes its earlier diagram ([1edc9b8](https://github.com/state-machines/state_machines-yard/commit/1edc9b87980d1202c72671deeb7c4494761bc557))
18
+ * code-valued state options and numeric names are documented as written ([d7a2c4b](https://github.com/state-machines/state_machines-yard/commit/d7a2c4b976b3cf5fd46258e9602660402e1a25f2))
19
+ * key documented machines by their fully qualified namespace ([5bf46b0](https://github.com/state-machines/state_machines-yard/commit/5bf46b095a91e9293cbdec8ae269bf8e16096aba))
20
+ * read callbacks through Callback#callables; require state_machines 0.303.0 ([8bd5e0d](https://github.com/state-machines/state_machines-yard/commit/8bd5e0db24a92e056fd53bf915c2d41dbb12f158))
21
+ * release-please bumps the gem version ([1115494](https://github.com/state-machines/state_machines-yard/commit/1115494011bf37913c7d5ff123a70b6e4f657dc6))
22
+ * reopened and inherited machines are documented as the core builds them ([84ac0ee](https://github.com/state-machines/state_machines-yard/commit/84ac0ee8d60e21cea536121af353a0b84a05ab2a))
23
+ * run RuboCop in the default task ([f5827cf](https://github.com/state-machines/state_machines-yard/commit/f5827cfb471d8ff14848fc562c3b94780226bf06))
24
+ * the Events text lists callbacks in the order the core runs them ([e568c5f](https://github.com/state-machines/state_machines-yard/commit/e568c5f9a0c665eba8b86d72fdaff423bc0a0496))
25
+
26
+ ## [0.2.0](https://github.com/state-machines/state_machines-yard/compare/v0.1.0...v0.2.0) (2026-10-18)
27
+
28
+
29
+ ### Features
30
+
31
+ * configurable renderer for yard diagrams ([3268679](https://github.com/state-machines/state_machines-yard/commit/326867993c1982bfc9fe2ccf406d6f3669f4608e))
32
+ * run tests with padded_cell on CRuby ([#13](https://github.com/state-machines/state_machines-yard/issues/13)) ([1b9201c](https://github.com/state-machines/state_machines-yard/commit/1b9201c114a1f8d28988430069527f1f7d1236dd))
33
+
34
+
35
+ ### Bug Fixes
36
+
37
+ * require state_machines-mermaid ([eea3f26](https://github.com/state-machines/state_machines-yard/commit/eea3f26d8a53689ad184cfc4fe201fa6406c9c05))
38
+
39
+ ## 0.1.0 (2025-03-18)
40
+
41
+
42
+ ### Features
43
+
44
+ * add tests ([37d6f34](https://github.com/state-machines/state_machines-yard/commit/37d6f3482d98222dfbb4940cf1f2ba846d95ca5f))
data/Gemfile CHANGED
@@ -1,2 +1,15 @@
1
+ # frozen_string_literal: true
2
+
1
3
  source 'https://rubygems.org'
2
4
  gemspec
5
+
6
+ platforms :mri do
7
+ gem 'padded_cell', '~> 0.2'
8
+ end
9
+
10
+ gem 'ruby-graphviz'
11
+
12
+ group :test do
13
+ gem 'state_machines-graphviz', '>= 0.2.0'
14
+ gem 'state_machines-mermaid', '>= 0.3.0'
15
+ end
data/LICENSE.txt CHANGED
@@ -1,5 +1,5 @@
1
1
  Copyright (c) 2006-2012 Aaron Pfeifer
2
- Copyright (c) 2014 Abdelkader Boudih
2
+ Copyright (c) 2014-2025 Abdelkader Boudih
3
3
 
4
4
  MIT License
5
5
 
data/README.md CHANGED
@@ -16,10 +16,59 @@ Or install it yourself as:
16
16
 
17
17
  $ gem install state_machines-yard
18
18
 
19
+ ## Events
20
+
21
+ Whatever the renderer, each class's documentation lists its machines' events, and
22
+ each event's method (`ignite`, `ignite!`) describes the transitions it performs: from
23
+ each state the first branch that matches, its guards and the callbacks that run on it in
24
+ the order the core runs them (an around where it enters),
25
+ and the `after_failure` callbacks:
26
+
27
+ * parked -> idling [if engine_ok? && if_any_state (gate=open, alarm=off)] / before check_mirrors, after log_start (if logging?)
28
+ * parked -> stalled / before check_mirrors
29
+
30
+ On failure: alert
31
+
32
+ The text is read through [state_machines-diagram](https://github.com/state-machines/state_machines-diagram),
33
+ so it labels guards and callbacks exactly as the diagrams do.
34
+
35
+ ## Diagrams
36
+
37
+ Diagrams are an optional extra. Set `STATE_MACHINES_RENDERER` to draw each documented machine:
38
+
39
+ * `graphviz` embeds a PNG drawn by [state_machines-graphviz](https://github.com/state-machines/state_machines-graphviz)
40
+ (needs the `dot` binary)
41
+ * `mermaid` embeds a Mermaid diagram drawn by [state_machines-mermaid](https://github.com/state-machines/state_machines-mermaid)
42
+ * `none` (the default) draws nothing
43
+
44
+ The plugin reads the state machine DSL without running it. Transitions carry the
45
+ guards the core runs: `if:`/`unless:` conditions (each one of an Array, a String
46
+ as the code it is, a lambda or other code by its source) and state guards
47
+ (`if_state`, `if_all_states`, `if_any_state`, `unless_state`, `unless_all_states`,
48
+ `unless_any_state`), each group with its requirements. A requirement or state guard
49
+ only known when the code runs (a constant, a method call) cannot be documented
50
+ faithfully, so that transition is left out with a warning; an initial state
51
+ written as code documents no state as initial.
52
+
53
+ Transition callbacks (`before_transition`, `after_transition`, `around_transition`,
54
+ `after_failure`) are read the same way: their methods (positional, `do:`, a block),
55
+ the transitions they run on (`from`/`to`/`on`, their `except_` forms, `a => b`
56
+ pairs) and their own conditions. Diagrams show them as the renderers label them:
57
+ a Symbol by name, String code as written, a block or lambda as `lambda@file:line`,
58
+ a conditional callback with its conditions. A diagram a renderer fails to draw is
59
+ left out with a warning; the rest of the class's documentation stands.
60
+
61
+ ## Testing
62
+
63
+ A comprehensive test suite is included for the gem. To run all tests:
64
+
65
+ ```
66
+ rake test
67
+ ```
19
68
 
20
69
  ## Contributing
21
70
 
22
- 1. Fork it ( https://github.com/seuros/state_machines-yard/fork )
71
+ 1. Fork it ( https://github.com/state-machines/state_machines-yard/fork )
23
72
  2. Create your feature branch (`git checkout -b my-new-feature`)
24
73
  3. Commit your changes (`git commit -am 'Add some feature'`)
25
74
  4. Push to the branch (`git push origin my-new-feature`)
data/Rakefile CHANGED
@@ -1 +1,30 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+ require 'shellwords'
6
+
7
+ Rake::TestTask.new(:minitest) do |t|
8
+ t.libs << 'test'
9
+ t.pattern = 'test/**/*_test.rb'
10
+ t.verbose = true
11
+ t.warning = false
12
+ end
13
+
14
+ # Both branches define :test, once per engine.
15
+ # rubocop:disable Rake/DuplicateTask
16
+ desc 'Run the test suite (padded_cell on CRuby, plain Minitest elsewhere)'
17
+ if RUBY_ENGINE == 'ruby'
18
+ task :test do
19
+ sh 'padded_cell', *Shellwords.split(ENV.fetch('TESTOPTS', ''))
20
+ end
21
+ else
22
+ task test: :minitest
23
+ end
24
+ # rubocop:enable Rake/DuplicateTask
25
+
26
+ require 'rubocop/rake_task'
27
+
28
+ RuboCop::RakeTask.new
29
+
30
+ task default: %i[test rubocop]
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'state_machines/diagram/introspection'
4
+
5
+ module StateMachines
6
+ module Yard
7
+ # A machine's events as text: the transitions each performs, as the core
8
+ # resolves them (from one source the first matching branch), with their
9
+ # guards and callbacks, labelled as the diagram renderers label them. The
10
+ # documentation carries this whatever renderer draws, or none.
11
+ module Description
12
+ Introspection = StateMachines::Diagram::Introspection
13
+ Labels = StateMachines::Diagram::Labels
14
+
15
+ module_function
16
+
17
+ # Each event as { name:, transitions: [line], failure: [callback] }, or
18
+ # { name:, error: } when the core refuses one of its conditions (a
19
+ # String it will not evaluate): it raises the same when it fires
20
+ def events(machine)
21
+ machine.events.map do |event|
22
+ { name: event.name.to_s,
23
+ transitions: Introspection.event_transitions(machine, event).map { transition(machine, event, *it) },
24
+ failure: failure_callbacks(machine, event) }
25
+ rescue SecurityError, ArgumentError => e
26
+ { name: event.name.to_s, error: e.message, transitions: [], failure: [] }
27
+ end
28
+ end
29
+
30
+ # "parked -> idling [if a && if_state gate=open] / before check, after log"
31
+ def transition(machine, event, from, to, branch)
32
+ guards = Labels.condition_phrases(Introspection.guard_conditions(branch))
33
+ callbacks = callback_steps(machine, from, to, event.name)
34
+ ["#{Labels.state_text(from)} -> #{Labels.state_text(to)}",
35
+ ("[#{guards.join(' && ')}]" if guards.any?),
36
+ ("/ #{callbacks.join(', ')}" if callbacks.any?)].compact.join(' ')
37
+ end
38
+
39
+ # The callbacks in the order the core runs them, each with its kind: an
40
+ # around where it enters (as Labels.action_list lists it), the afters
41
+ # after the state change: "around time, before check, after log"
42
+ def callback_steps(machine, from, to, event_name)
43
+ Introspection.callback_sequence(machine, from, to, event_name)
44
+ .reject { it[:phase] == :exit }
45
+ .map { "#{it[:kind]} #{Labels.callback_text(it)}" }
46
+ end
47
+
48
+ # The after_failure callbacks that run when the event fails
49
+ def failure_callbacks(machine, event)
50
+ machine.callbacks[:failure].select { it.branch.matches?(nil, on: event.name, guard: false) }
51
+ .flat_map do |callback|
52
+ conditions = Introspection.guard_conditions(callback.branch)
53
+ callback.callables.map do |method|
54
+ Labels.callback_text(label: Labels.action_label(method), conditions: conditions)
55
+ end
56
+ end
57
+ end
58
+
59
+ # The event's description lines for its methods' docstrings
60
+ def docstring_lines(event)
61
+ lines = if event[:error]
62
+ ['', "Its transitions cannot be described: #{event[:error]}"]
63
+ elsif event[:transitions].empty?
64
+ ['', 'No transitions: it never fires.']
65
+ else
66
+ ['', 'Transitions (from each state the first that matches is taken):', '',
67
+ *event[:transitions].map { "* #{it}" }]
68
+ end
69
+ lines += ['', "On failure: #{event[:failure].join(', ')}"] if event[:failure].any?
70
+ lines + ['']
71
+ end
72
+ end
73
+ end
74
+ end
@@ -1,33 +1,134 @@
1
- module StateMachine
2
- module YARD
1
+ # frozen_string_literal: true
2
+
3
+ require 'prism'
4
+
5
+ module StateMachines
6
+ module Yard
3
7
  module Handlers
4
- # Handles and processes nodes
5
- class Base < ::YARD::Handlers::Ruby::Base
8
+ # Handles and processes nodes. A handler reads its call's arguments
9
+ # from the source with Prism and takes only what is written as a
10
+ # literal: nothing in the documented code is run.
11
+ class Base < YARD::Handlers::Ruby::Base
12
+ # An argument that is not a literal, so its value is only known when
13
+ # the code runs
14
+ class Unreadable < StandardError; end
15
+
16
+ # Code the documented source holds where the core takes a value (a
17
+ # state's value: or human_name:), shown as it is written
18
+ Code = Data.define(:source) do
19
+ def to_s = source
20
+ def inspect = source
21
+ end
22
+
23
+ # The literals Ruby spells as keywords
24
+ KEYWORDS = { Prism::NilNode => nil, Prism::TrueNode => true, Prism::FalseNode => false }.freeze
25
+ NUMBERS = [Prism::IntegerNode, Prism::FloatNode].freeze
26
+ # The literals a name can be
27
+ NAMES = [Symbol, String, Integer, Float, TrueClass, FalseClass].freeze
28
+ # Text literals, and how each turns its text into its value
29
+ TEXTS = { Prism::SymbolNode => :to_sym, Prism::StringNode => :itself }.freeze
6
30
 
7
31
  private
8
32
 
9
- # Extracts the value from the node as either a string or symbol
10
- def extract_node_name(ast)
11
- case ast.type
12
- when :symbol_literal
13
- ast.jump(:ident).source.to_sym
14
- when :string_literal
15
- ast.jump(:tstring_content).source
16
- else
17
- nil
33
+ # The handled call as Prism reads it
34
+ def call_node
35
+ @call_node ||= begin
36
+ node = Prism.parse(statement.source).value.statements.body.first
37
+ raise Unreadable, "`#{statement.source}` is not a plain call" unless node.is_a?(Prism::CallNode)
38
+
39
+ node
18
40
  end
19
41
  end
20
42
 
21
- # Extracts the values from the node as either strings or symbols.
22
- # If the node isn't an array, it'll be converted to an array.
23
- def extract_node_names(ast, convert_to_array = true)
24
- if [nil, :array].include?(ast.type)
25
- ast.children.map { |child| extract_node_name(child) }
26
- else
27
- node_name = extract_node_name(ast)
28
- convert_to_array ? [node_name] : node_name
43
+ # The call's positional arguments, as nodes
44
+ def positional_arguments
45
+ arguments = call_node.arguments&.arguments || []
46
+ options_node?(arguments.last) ? arguments[0...-1] : arguments
47
+ end
48
+
49
+ # The call's trailing options Hash, as [key node, value node] pairs
50
+ def option_pairs
51
+ last = call_node.arguments&.arguments&.last
52
+ options_node?(last) ? pairs(last) : []
53
+ end
54
+
55
+ def options_node?(node)
56
+ node.is_a?(Prism::KeywordHashNode) || node.is_a?(Prism::HashNode)
57
+ end
58
+
59
+ def pairs(node)
60
+ node.elements.map do |element|
61
+ unreadable(element) unless element.is_a?(Prism::AssocNode)
62
+
63
+ [element.key, element.value]
29
64
  end
30
65
  end
66
+
67
+ # The value of a literal: a Symbol, String, nil, true, false, number,
68
+ # or an Array or Hash of those
69
+ def literal(node)
70
+ case node
71
+ when *TEXTS.keys then node.unescaped.public_send(TEXTS.fetch(node.class))
72
+ when *KEYWORDS.keys then KEYWORDS.fetch(node.class)
73
+ when *NUMBERS then node.value
74
+ when Prism::ArrayNode then node.elements.map { literal(it) }
75
+ when Prism::HashNode then pairs(node).to_h { |key, value| [literal(key), literal(value)] }
76
+ else unreadable(node)
77
+ end
78
+ end
79
+
80
+ # A state, event or machine name: any literal the core takes as one,
81
+ # a Symbol, String, number, true or false (or nil, the nil state,
82
+ # when +nil_allowed+)
83
+ def name_literal(node, nil_allowed: false)
84
+ value = literal(node)
85
+ return value if NAMES.any? { value.is_a?(it) } || (nil_allowed && value.nil?)
86
+
87
+ unreadable(node)
88
+ end
89
+
90
+ # The names one argument gives: a name, or an Array of them
91
+ def names_in(node, nil_allowed: false)
92
+ return [name_literal(node, nil_allowed: nil_allowed)] unless node.is_a?(Prism::ArrayNode)
93
+
94
+ node.elements.map { name_literal(it, nil_allowed: nil_allowed) }
95
+ end
96
+
97
+ # The literal options among +keys+; any other option is left out. An
98
+ # option written as code is a Code of its source when it is one of
99
+ # +code+, and otherwise left out; either way with a warning, since
100
+ # the documentation cannot show its value.
101
+ def literal_options(keys, code: [])
102
+ option_pairs.each_with_object({}) do |(key, value), options|
103
+ name = literal(key)
104
+ next unless keys.include?(name)
105
+
106
+ options[name] = option_literal(name, value, code)
107
+ rescue Unreadable
108
+ next
109
+ end
110
+ end
111
+
112
+ def option_literal(name, node, code)
113
+ literal(node)
114
+ rescue Unreadable
115
+ documented = code.include?(name) ? 'documented as its source' : 'left out'
116
+ log.warn "state_machines-yard: #{name}: is code (`#{node.slice}`), #{documented} " \
117
+ "(#{parser.file}:#{statement.line})"
118
+ raise unless code.include?(name)
119
+
120
+ Code.new(node.slice)
121
+ end
122
+
123
+ def unreadable(node)
124
+ raise Unreadable, "`#{node.slice}` is code, not a literal"
125
+ end
126
+
127
+ # Logs that +what+ is left out of the documentation, and why
128
+ def skip(what, error)
129
+ log.warn "state_machines-yard: #{what} is not documented: #{error.message} " \
130
+ "(#{parser.file}:#{statement.line})"
131
+ end
31
132
  end
32
133
  end
33
134
  end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module StateMachines
4
+ module Yard
5
+ module Handlers
6
+ # Handles and processes the transition callbacks: before_transition,
7
+ # after_transition, around_transition and after_failure. The
8
+ # documented machine gets each callback with the methods it runs, the
9
+ # transitions it runs on (from/to/on and their except_ forms, or
10
+ # implicit from => to pairs) and its own conditions, read as the core
11
+ # reads a transition's.
12
+ class Callback < Base
13
+ include Requirements
14
+
15
+ # The DSL method of each callback kind
16
+ KINDS = %i[before_transition after_transition around_transition after_failure].freeze
17
+ # Options the core takes that change how a callback runs, not when
18
+ BEHAVIOUR = %i[bind_to_object terminator].freeze
19
+
20
+ KINDS.each { handles method_call(it) }
21
+
22
+ # Store the handled method name for testing
23
+ @handles_method = KINDS
24
+
25
+ def process
26
+ return unless owner.is_a?(StateMachines::Machine)
27
+
28
+ owner.public_send(call_node.name, **callback_options)
29
+ rescue Unreadable, ArgumentError => e
30
+ # A callback that cannot be read, or that the core refuses, would be
31
+ # documented as running on other transitions or methods than it does
32
+ skip(call_node.name.to_s, e)
33
+ end
34
+
35
+ private
36
+
37
+ def callback_options
38
+ methods = positional_arguments.map { action(it) }
39
+ options = option_pairs.each_with_object({}) do |(key, value), read|
40
+ name = requirement(key)
41
+ next if BEHAVIOUR.include?(name)
42
+
43
+ if name == :do
44
+ methods.concat(action_list(value))
45
+ else
46
+ read[name] = option_value(name, value)
47
+ end
48
+ end
49
+ methods << block_action(call_node.block) if call_node.block
50
+ options.merge(do: methods)
51
+ end
52
+
53
+ def action_list(node)
54
+ node.is_a?(Prism::ArrayNode) ? node.elements.map { action(it) } : [action(node)]
55
+ end
56
+
57
+ # A method the callback runs, as the core reads it: a Symbol names a
58
+ # method, a String is code. A lambda or proc is shown as diagrams show
59
+ # a Proc, by where it is defined; any other code by its source.
60
+ def action(node)
61
+ case node
62
+ when Prism::SymbolNode, Prism::StringNode then literal(node)
63
+ else proc_literal?(node) ? lambda_label(node.location.start_line) : node.slice
64
+ end
65
+ end
66
+
67
+ # ->, lambda {}, proc {} or Proc.new {}
68
+ def proc_literal?(node)
69
+ return true if node.is_a?(Prism::LambdaNode)
70
+ return false unless node.is_a?(Prism::CallNode) && node.block
71
+
72
+ node.receiver.nil? ? %i[lambda proc].include?(node.name) : proc_new?(node)
73
+ end
74
+
75
+ def proc_new?(node)
76
+ node.name == :new && node.receiver.slice == 'Proc'
77
+ end
78
+
79
+ # The callback's own block, or a block argument: &:name as diagrams
80
+ # show a Symbol's proc, anything else as an action
81
+ def block_action(node)
82
+ return lambda_label(node.location.start_line) if node.is_a?(Prism::BlockNode)
83
+
84
+ expression = node.expression
85
+ expression.is_a?(Prism::SymbolNode) ? "&#{expression.slice}" : action(expression)
86
+ end
87
+
88
+ # "lambda@file:line", the label diagrams give a Proc; +line+ counts
89
+ # from the start of the statement
90
+ def lambda_label(line)
91
+ "lambda@#{File.basename(parser.file.to_s)}:#{statement.line + line - 1}"
92
+ end
93
+ end
94
+ end
95
+ end
96
+ end
@@ -1,23 +1,32 @@
1
- module StateMachine
2
- module YARD
1
+ # frozen_string_literal: true
2
+
3
+ module StateMachines
4
+ module Yard
3
5
  module Handlers
4
6
  # Handles and processes #event
5
7
  class Event < Base
6
8
  handles method_call(:event)
7
9
 
10
+ # Store the handled method name for testing
11
+ @handles_method = :event
12
+
8
13
  def process
9
- if owner.is_a?(StateMachines::Machine)
10
- handler = self
11
- statement = self.statement
12
- names = extract_node_names(statement.parameters(false))
14
+ return unless owner.is_a?(StateMachines::Machine)
15
+
16
+ handler = self
17
+ block = statement.block
18
+ names = positional_arguments.flat_map { names_in(it) }
19
+ options = literal_options(%i[human_name], code: %i[human_name])
13
20
 
14
- names.each do |name|
15
- owner.event(name) do
16
- # Parse the block
17
- handler.parse_block(statement.last.last, owner: self)
18
- end
21
+ names.each do |name|
22
+ owner.event(name, **options) do
23
+ handler.parse_block(block.last, owner: self) if block
19
24
  end
20
25
  end
26
+ rescue Unreadable, ArgumentError => e
27
+ # One the core refuses (a name of another type than the others) is
28
+ # not documented as something else
29
+ skip('event', e)
21
30
  end
22
31
  end
23
32
  end