Tidied up the let clauses in edge_spec
[graph.njae.git] / lib / graph.njae / edge.rb
1 # A simple graph library
2
3 module GraphNjae
4
5 # An edge (or multiedge) in a graph. The edge can have arbitrary attributes,
6 # treated as method names.
7 #
8 # Each connection is handled by a Graph::Connection object, so that each end
9 # of the Edge can have it's own attributes.
10 class Edge < OpenStruct
11 def initialize(values = {})
12 super(values)
13 self.connections = []
14 self
15 end
16
17 # Connect this edge to a vertex
18 def <<(other)
19 c = Connection.new
20 c.end = other
21 other.edges << self unless other.edges.include? self
22 self.connections << c
23 self
24 end
25
26 # Return the set of vertices this edge connects.
27 def vertices
28 self.connections.map {|c| c.end}
29 end
30
31 # Return the connection object that joins this Edge to the specified Vertex
32 def connection_at(vertex)
33 self.connections.find {|c| c.end.equal? vertex}
34 end
35
36 # Return the vertex at the other end of the one given.
37 # Self-loops should still return the vertex
38 def other_end(vertex)
39 if self.vertices[0] == vertex
40 self.vertices[1]
41 else
42 self.vertices[0]
43 end
44 end
45
46 def to_s
47 '<E: ' + self.type.to_s + ' [' + self.vertices.map {|n| n.to_s}.join(', ') + '] >'
48 end
49
50 def to_dot(opts = {})
51 if block_given?
52 yield self
53 else
54 dot = self.connections[0].end.object_id.to_s + " -- " + self.connections[1].end.object_id.to_s
55 if opts.size > 0
56 dot << ' {'
57 dot << opts.keys.map { |k|
58 (k.to_s + ' = "' + self.instance_eval(opts[k].to_s).to_s) + '"'
59 }.join(', ')
60 dot << '}'
61 end
62 dot << ';'
63 end
64 end
65
66 end
67
68 # A connection between an Edge and a Vertex.The connection can have arbitrary attributes,
69 # treated as method names.
70 class Connection < OpenStruct
71 def initialize(values = {})
72 super(values)
73 self
74 end
75 end
76 end