Class: Society::ObjectGraph

Inherits:
Array
  • Object
show all
Defined in:
lib/society/object_graph.rb

Overview

The ObjectGraph class represents a graph of interrelated nodes as an Array of nodes which can be iterated over.

Instance Method Summary collapse

Constructor Details

#initialize(*nodes) ⇒ ObjectGraph

Public: Override Array#initialize, accepting any number of nodes and lists of nodes including other ObjectGraphs to create a single graph from them.

nodes - Any number of nodes or lists of nodes.



12
13
14
# File 'lib/society/object_graph.rb', line 12

def initialize(*nodes)
  super(nodes.flatten)
end

Instance Method Details

#+(other) ⇒ Object

Public: Add two graphs together, returning a new ObjectGraph containing the sum of all nodes contained in both.

other - Another graph.

Returns an ObjectGraph.



22
23
24
25
26
27
28
29
30
# File 'lib/society/object_graph.rb', line 22

def +(other)
  other.reduce(self) do |graph, node|
    if graph.select { |n| n.intersects?(node) }.any?
      Society::ObjectGraph.new(graph.map { |n| n + node || n  })
    else
      Society::ObjectGraph.new(graph, node)
    end
  end
end

#<<(node) ⇒ Object Also known as: push

Public: Create a new graph, adding another node.

node - Node to be added to the new graph.

Returns an ObjectGraph.



37
38
39
# File 'lib/society/object_graph.rb', line 37

def <<(node)
  self + Society::ObjectGraph.new(node)
end

#to_hObject

Public: Return the graph represented as a Hash.

Returns a hash.



45
46
47
48
49
# File 'lib/society/object_graph.rb', line 45

def to_h
  self.reduce({}) do |hash, node|
    hash.merge({ node.name => node.edges })
  end
end

#to_jsonObject

Public: Return the graph as a JSON string.

Returns a string.



54
55
56
57
58
59
60
61
62
# File 'lib/society/object_graph.rb', line 54

def to_json
  to_h.reduce({}) do |hash, node|
    name, edges_raw = node
    edges = edges_raw.reduce({}) do |edges, edge|
      edges.merge({ edge.to => edge.weight })
    end
    hash.merge({ name => edges })
  end.to_json
end