Class: ChartHelpers::Parsers::Graphviz

Inherits:
Object
  • Object
show all
Defined in:
lib/chart_helpers/parsers/graphviz.rb

Constant Summary collapse

CONNECTOR_REGEX =
%r{
  (?<connector>
    --(?<text>\w+)-->|
    -->|
    --(?<text>\w+)---|
    ---|
    -\.(?<text>\w+)\.->|
    -\.->|
    ==(?<text>\w+)===>|
    ==>
  )
}x

Class Method Summary collapse

Class Method Details

.parse(lines) ⇒ Object



6
7
8
9
10
11
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
# File 'lib/chart_helpers/parsers/graphviz.rb', line 6

def self.parse(lines)
  graphs = { default_global_data: [] }
  nodes = Set.new
  in_subgraph = false

  while line = lines.shift
    next if line.empty? || line.nil?
    line.strip!

    case line
    when /\Asubgraph/
      subgraph_title = line.split('subgraph')[1..-1].join('subgraph').strip
      graphs[subgraph_title] ||= []
      current_subgraph = subgraph_title
    when /\Aend/
      raise 'Not in subgraph' unless current_subgraph
      current_subgraph = nil
    else
      line = parse_line(line)
      if current_subgraph
        graphs[subgraph_title] << line
      else
        graphs[:default_global_data] << line
      end
      nodes.add(line[:from_node])
      nodes.add(line[:to_node])
    end
  end

  raise 'Never finished subgraph' if in_subgraph
  [graphs, nodes]
end

.parse_line(line, date: false) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/chart_helpers/parsers/graphviz.rb', line 52

def self.parse_line(line, date: false)
  match_data = line.match(CONNECTOR_REGEX)
  text = match_data[:text]
  connector = match_data[:connector]
  parts = line.split(connector)

  style = if connector.start_with?('==')
    'bold'
  elsif connector.start_with?('-.')
    'dotted'
  else
    ''
  end

  { 
    from_node: parts.first,
    to_node: parts.last,
    line_text: match_data[:text],
    connector: connector,
    style: style
  }
end