Class: Aquanaut::Graph

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/aquanaut/graph.rb

Overview

A graph representing the sitemap in terms of a data structure. A hash is used internally to make the nodes accessible through the URIs.

Instance Method Summary collapse

Constructor Details

#initializeGraph

Returns a new instance of Graph.



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

def initialize
  @nodes = Hash.new
end

Instance Method Details

#[](uri) ⇒ Object

Accessor method to retrieve nodes by their URI.

Parameters:

  • uri (URI)

    the URI representing the node.



37
38
39
# File 'lib/aquanaut/graph.rb', line 37

def [](uri)
  @nodes[uri]
end

#add_edge(predecessor_uri, successor_uri) ⇒ Object

Use this method to easily add new edges without the need to pass actual node objects. The method delegates the edge creation to the dedicated node edge method.

Parameters:

  • predecessor_uri (URI)

    source node for the edge

  • successor_uri (URI)

    target node for the edge



29
30
31
# File 'lib/aquanaut/graph.rb', line 29

def add_edge(predecessor_uri, successor_uri)
  @nodes[predecessor_uri].add_edge(@nodes[successor_uri])
end

#add_node(node) ⇒ Object

Use this method for making nodes available in the graph. New nodes are only assigned once.

Parameters:

  • node (Node)

    the node to add to the graph.



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

def add_node(node)
  @nodes[node.uri] ||= node
end

#eachObject

Accessor method to iterate the nodes and their adjacency list.



43
44
45
46
47
# File 'lib/aquanaut/graph.rb', line 43

def each
  @nodes.values.each do |node|
    yield node, node.adjacency_list
  end
end

#to_jsonObject

Used for visualizing the graph on the front-end.



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

def to_json
  model = { 'nodes' => [], 'links' => [] }

  self.each do |node, adjacency|
    if node.instance_of?(Aquanaut::PageNode)
      group = 1
    else
      asset_groups = { 'image' => 2, 'stylesheet' => 3 }
      group = asset_groups[node.type]
    end

    model['nodes'] << { 'name' => node.uri, 'group' => group }
    source = @nodes.values.index(node)

    adjacency.each do |adjacency_node|
      target = @nodes.values.index(adjacency_node)
      model['links'] << { 'source' => source, 'target' => target }
    end
  end

  return model.to_json
end