File: dot_script.rb

package info (click to toggle)
ruby-graphviz 1.2.5-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,216 kB
  • sloc: ruby: 7,685; xml: 26; makefile: 17
file content (109 lines) | stat: -rw-r--r-- 2,156 bytes parent folder | download | duplicates (4)
1
2
3
4
5
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
require "forwardable"
class GraphViz

  class DOTScriptData
    attr_accessor :type
    def initialize(type = nil)
      @data = []
      @separator = ""
      @type = type
    end

    def append(data)
      @data << data
    end
    alias :<< :append

    def add_attribute(name, value)
      @data << @separator << name << " = " << value
      @separator = determine_separator
    end

    def to_str
      case @type
        when "graph_attr" then "#{@data.join}#{@separator}"
        when "node_attr" then "node[#{@data.join(' ')}];"
        when "edge_attr" then "edge[#{@data.join(' ')}];"
        else raise ArgumentError, "Wrong type: #{@type}."
      end
    end
    alias :to_s :to_str

    def empty?
      @data.empty?
    end

    private

    def determine_separator
      case @type
        when "graph_attr"             then ";\n"
        when "node_attr", "edge_attr" then ","
        else raise ArgumentError, "Wrong type: #{@type}."
      end
    end

  end

  class DOTScript
    extend Forwardable

    def_delegators :@script, :end_with?

    def initialize
      @script = ''
    end

    def append(line)
      @script << assure_ends_with(line.to_s,"\n")

      self
    end
    alias :<< :append

    def prepend(line)
      @script = assure_ends_with(line.to_s,"\n") + @script

      self
    end

    def make_subgraph(name)
      prepend(assure_ends_with("subgraph #{name}"," {"))
    end

    def add_type(type, data)
      return self if data.empty?

      case type
      when "graph_attr"
        append_statement("  " + data)
      when "node_attr"
        append_statement("  node [" + data + "]")
      when "edge_attr"
        append_statement("  edge [" + data + "]")
      else
        raise ArgumentError,
          "Unknown type: #{type}." <<
          "Possible: 'graph_attr','node_attr','edge_attr'"
      end

      self
    end

    def to_str
      @script
    end
    alias :to_s :to_str

    private

    def assure_ends_with(str,ending="\n")
      str.to_s.end_with?("\n") ? str : str + ending
    end

    def append_statement(statement)
      append(assure_ends_with(statement, ";\n"))
    end

  end
end