Class: Hooked::Graph

Inherits:
Object
  • Object
show all
Includes:
TSort
Defined in:
lib/hooked/graph.rb

Defined Under Namespace

Classes: CircularDependencyError, Node

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Graph) initialize

A new instance of Graph



13
14
15
# File 'lib/hooked/graph.rb', line 13

def initialize
  @input = []
end

Instance Attribute Details

- (Object) input (readonly)

Returns the value of attribute input



11
12
13
# File 'lib/hooked/graph.rb', line 11

def input
  @input
end

- (Object) output (readonly)

Returns the value of attribute output



11
12
13
# File 'lib/hooked/graph.rb', line 11

def output
  @output
end

Instance Method Details

- (Object) <<(node)



17
18
19
20
# File 'lib/hooked/graph.rb', line 17

def <<(node)
  @changed = true
  @input << node
end

- (Boolean) changed?

Returns:

  • (Boolean)


22
23
24
# File 'lib/hooked/graph.rb', line 22

def changed?
  !!@changed
end

- (Object) sort



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
# File 'lib/hooked/graph.rb', line 26

def sort
  do_sort = input.any? do |n|
    !n.dependencies[:before].empty? || !n.dependencies[:after].empty?
  end

  if do_sort
    @nodes = input.inject({}) do |nodes, node|
      children = node.dependencies[:after].map {|d| d.object_id }
      nodes[node.advice.object_id] = Node.new(children, node); nodes
    end
    
    @nodes.each do |name, node|
      node.node.dependencies[:before].each do |dep|
        dep_name = dep.object_id
        next unless @nodes[dep_name]
        @nodes[dep_name].children << name
      end
    end
    
    strongly_connected_components.each do |name|
      next unless Array === name && name.length > 1
      raise CircularDependencyError, "Sorting failed: #{name.map {|n|
        @nodes[n].node.advice.inspect }.join ', '}"
    end
    
    @output = tsort.map {|name| @nodes[name].node }
  else
    @output = input.reverse
  end
  
  @changed = false
end

- (Object) tsort_each_child(name, &block)



63
64
65
# File 'lib/hooked/graph.rb', line 63

def tsort_each_child(name, &block)
  @nodes[name].children.each &block if @nodes[name]
end

- (Object) tsort_each_node(&block)



59
60
61
# File 'lib/hooked/graph.rb', line 59

def tsort_each_node(&block)
  @nodes.each_key &block
end