Class: Graphdown::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/graphdown/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



5
6
7
# File 'lib/graphdown/parser.rb', line 5

def initialize
  @graph = Graph.new
end

Instance Attribute Details

#graphObject (readonly)

Returns the value of attribute graph.



3
4
5
# File 'lib/graphdown/parser.rb', line 3

def graph
  @graph
end

Instance Method Details

#outputObject



36
37
38
39
40
41
# File 'lib/graphdown/parser.rb', line 36

def output
  @graph.layer_nodes
  @graph.layout_nodes
  @graph.layout_edges
  @graph.to_svg
end

#parse(text) ⇒ Object



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
# File 'lib/graphdown/parser.rb', line 9

def parse(text)
  tokens = text.split(/(?<=[\]>])\s+/)
  2.step(tokens.size, 2) do |n|
    # origins
    origin_labels = tokens[n - 2].scan(/(?<=\[).+?(?=\])/)
    origins = origin_labels.map do |label|
      @graph.find_node_by_label(label) || Node.new(label)
    end

    # targets
    target_labels = tokens[n].scan(/(?<=\[).+?(?=\])/)
    targets = target_labels.map do |label|
      @graph.find_node_by_label(label) || Node.new(label)
    end

    # edges
    direction = (tokens[n - 1] == "<->") ? :two_way : :forward
    origins.each do |origin|
      @graph << origin
      targets.each do |target|
        origin.connect(target, direction)
        @graph << target
      end
    end
  end
end