Class: Graph

Inherits:
Hash
  • Object
show all
Defined in:
lib/sql_dep_grapher/graph.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGraph

Returns a new instance of Graph.



12
13
14
15
16
17
18
# File 'lib/sql_dep_grapher/graph.rb', line 12

def initialize
  super { |h,k| h[k] = [] }
  @prefix = []
  @attribs = Hash.new { |h,k| h[k] = [] }
  @edge = Hash.new { |h,k| h[k] = Hash.new { |h2,k2| h2[k2] = [] } }
  @order = []
end

Instance Attribute Details

#attribsObject (readonly)

Returns the value of attribute attribs.



7
8
9
# File 'lib/sql_dep_grapher/graph.rb', line 7

def attribs
  @attribs
end

#edgeObject (readonly)

Returns the value of attribute edge.



10
11
12
# File 'lib/sql_dep_grapher/graph.rb', line 10

def edge
  @edge
end

#orderObject (readonly)

Returns the value of attribute order.



9
10
11
# File 'lib/sql_dep_grapher/graph.rb', line 9

def order
  @order
end

#prefixObject (readonly)

Returns the value of attribute prefix.



8
9
10
# File 'lib/sql_dep_grapher/graph.rb', line 8

def prefix
  @prefix
end

Instance Method Details

#[]=(key, val) ⇒ Object



20
21
22
23
# File 'lib/sql_dep_grapher/graph.rb', line 20

def []=(key, val)
  @order << key unless self.has_key? key
  super(key, val)
end

#countsObject



41
42
43
44
45
46
47
# File 'lib/sql_dep_grapher/graph.rb', line 41

def counts
  result = Hash.new(0)
  each_pair do |from, to|
    result[from] += 1
  end
  result
end

#each_pairObject



25
26
27
28
29
30
31
# File 'lib/sql_dep_grapher/graph.rb', line 25

def each_pair
  @order.each do |from|
    self[from].each do |to|
      yield(from, to)
    end
  end
end

#invertObject



33
34
35
36
37
38
39
# File 'lib/sql_dep_grapher/graph.rb', line 33

def invert
  result = self.class.new
  each_pair do |from, to|
    result[to] << from
  end
  result
end

#keys_by_countObject



49
50
51
# File 'lib/sql_dep_grapher/graph.rb', line 49

def keys_by_count
  counts.sort_by { |x,y| y }.map {|x| x.first }
end

#save(path, type = "png") ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/sql_dep_grapher/graph.rb', line 72

def save(path, type="png")
  File.open(path + ".dot", "w") do |f|
    f.puts self.to_s
    f.flush
    cmd = "/usr/local/bin/dot -T#{type} #{path}.dot > #{path}.#{type}"
    system cmd
  end
end

#to_sObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/sql_dep_grapher/graph.rb', line 53

def to_s
  result = []
  result << "digraph absent"
  result << "  {"
  @prefix.each do |line|
    result << line
  end
  @attribs.sort.each do |node, attribs|
    result << "    #{node.inspect} [ #{attribs.join(',')} ]"
  end
  each_pair do |from, to|
    edge = @edge[from][to].join(", ")
    edge = " [ #{edge} ]" unless edge.empty?
    result << "    #{from.inspect} -> #{to.inspect}#{edge};"
  end
  result << "  }"
  result.join("\n")
end