Module: Philiprehberger::StateMachine::GraphExport

Defined in:
lib/philiprehberger/state_machine/graph_export.rb

Overview

Generates DOT/GraphViz output for state machine visualization.

Class Method Summary collapse

Class Method Details

.to_dot(definition, name: 'StateMachine') ⇒ String

Generate a DOT-format string representing the state machine.

Parameters:

  • definition (Definition)

    the state machine definition

  • name (String) (defaults to: 'StateMachine')

    graph name

Returns:

  • (String)

    DOT format string



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/philiprehberger/state_machine/graph_export.rb', line 12

def self.to_dot(definition, name: 'StateMachine')
  lines = []
  lines << "digraph #{name} {"
  lines << '  rankdir=LR;'
  lines << ''

  # Initial state indicator
  lines << '  __start__ [shape=point, width=0.2];'
  lines << "  __start__ -> #{definition.initial};"
  lines << ''

  # State nodes
  definition.all_states.each do |state|
    lines << "  #{state} [shape=ellipse];"
  end
  lines << ''

  # Transitions
  definition.events.each do |event_name, transitions|
    transitions.each do |t|
      Array(t.from).each do |from_state|
        guard_label = t.guard ? ' [guarded]' : ''
        lines << "  #{from_state} -> #{t.to} [label=\"#{event_name}#{guard_label}\"];"
      end
    end
  end

  # Auto-transitions
  if definition.respond_to?(:auto_transitions) && definition.auto_transitions.any?
    definition.auto_transitions.each do |at|
      Array(at.from).each do |from_state|
        lines << "  #{from_state} -> #{at.to} [label=\"auto(#{at.after}s)\", style=dashed];"
      end
    end
  end

  lines << '}'
  lines.join("\n")
end