Class: Gold::Diagram

Inherits:
Object
  • Object
show all
Defined in:
lib/gold/diagram.rb

Overview

Renders graphs of ‘Statesman::Machine`s.

Instance Method Summary collapse

Constructor Details

#initialize(machine, node_callback: nil, edge_callback: nil) ⇒ Diagram

Prepares to render a diagram from a ‘Statesman::Machine` class.



7
8
9
10
11
# File 'lib/gold/diagram.rb', line 7

def initialize(machine, node_callback: nil, edge_callback: nil)
  @machine = machine
  @node_callback = node_callback
  @edge_callback = edge_callback
end

Instance Method Details

#render(output) ⇒ Object

Renders a diagram and saves it to a SVG stored at ‘output`.



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
# File 'lib/gold/diagram.rb', line 14

def render(output)
  g = GraphViz.new(@machine.to_s, type: :digraph)

  # Mark the start of the state machine with a "start" label and arrow to the
  # initial state.
  g.add_node("start", shape: :plaintext)
  g.add_edge("start", @machine.initial_state)

  # Add all of the states as nodes.
  @machine.states.each do |state|
    node = g.add_node(state)
    @node_callback&.call(node)
  end

  # Add edges between connected states.
  @machine.successors.each do |state, successors|
    successors.each do |successor|
      edge = g.add_edge(state, successor)
      @edge_callback&.call(edge)
    end
  end

  # Save the output to a file.
  g.output(svg: output)
end