Merged in SimpleCov from master#
[graph.njae.git] / lib / graph.njae / vertex.rb
1 # A simple graph library
2
3 module GraphNjae
4 # A vertex in a graph. The edge can have arbitrary attributes,treated as
5 # method names.
6 class Vertex < OpenStruct
7 def initialize(values = {})
8 super(values)
9 self.edges = []
10 self
11 end
12
13 # Connect this vertex to another, creating an Edge to do so, and returning
14 # the Edge
15 def connect(other, edge_attributes = {})
16 e = Edge.new edge_attributes
17 e << self << other
18 # self.edges << e
19 # other.edges << e unless self === other
20 e
21 end
22
23 # Connect this vertex to another, creating an Edge to do so, and returning
24 # this Vertex
25 def <<(other)
26 connect(other)
27 self
28 end
29
30 # Return the set of neighbouring vertices
31 def neighbours
32 #vertices = self.edges.map {|e| e.vertices}.flatten
33 #vertices_to_me = vertices.select {|v| v == self}
34 #other_vertices = vertices.select {|v| v != self}
35 #(vertices_to_me[1..-1] || []) + other_vertices#
36 self.edges.map {|e| e.vertices.take_while {|v| v != self} +
37 e.vertices.drop_while {|v| v != self}[1..-1]}.flatten
38 end
39
40 def to_s
41 '<V: ' + self.name.to_s + '>'
42 end
43
44 def to_dot(opts = {})
45 if block_given?
46 yield self
47 else
48 dot = self.object_id.to_s
49 if opts.size > 0
50 dot << ' {'
51 dot << opts.keys.map { |k|
52 (k.to_s + ' = "' + self.instance_eval(opts[k].to_s).to_s) + '"'
53 }.join(', ')
54 dot << '}'
55 end
56 dot << ';'
57 end
58 end
59
60 end
61 end