Class: Aquanaut::Graph
- Inherits:
-
Object
- Object
- Aquanaut::Graph
- 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
-
#[](uri) ⇒ Object
Accessor method to retrieve nodes by their URI.
-
#add_edge(predecessor_uri, successor_uri) ⇒ Object
Use this method to easily add new edges without the need to pass actual node objects.
-
#add_node(node) ⇒ Object
Use this method for making nodes available in the graph.
-
#each ⇒ Object
Accessor method to iterate the nodes and their adjacency list.
-
#initialize ⇒ Graph
constructor
A new instance of Graph.
-
#to_json ⇒ Object
Used for visualizing the graph on the front-end.
Constructor Details
#initialize ⇒ Graph
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.
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.
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.
18 19 20 |
# File 'lib/aquanaut/graph.rb', line 18 def add_node(node) @nodes[node.uri] ||= node end |
#each ⇒ Object
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_json ⇒ Object
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 |