4a1ba790d4f33570f53525cbd3f3c23660135240
[graph.njae.git] / lib / graph.njae / edge.rb
1 require 'ostruct'
2
3 # A simple graph library
4
5 module GraphNjae
6
7 # An edge (or multiedge) in a graph. The edge can have arbitrary attributes,
8 # treated as method names.
9 #
10 # Each connection is handled by a Graph::Connection object, so that each end
11 # of the Edge can have it's own attributes.
12 class Edge < OpenStruct
13 def initialize(values = {})
14 super(values)
15 self.connections = []
16 self
17 end
18
19 # Connect this edge to a vertex
20 def <<(other)
21 c = Connection.new
22 c.end = other
23 other.edges << self unless other.edges.include? self
24 self.connections << c
25 self
26 end
27
28 # Return the set of vertices this edge connects.
29 def vertices
30 self.connections.map {|c| c.end}
31 end
32
33 # Return the connection object that joins this Edge to the specified Vertex
34 def connection_at(vertex)
35 self.connections.find {|c| c.end.equal? vertex}
36 end
37 end
38
39 # A connection between an Edge and a Vertex.The connection can have arbitrary attributes,
40 # treated as method names.
41 class Connection < OpenStruct
42 def initialize(values = {})
43 super(values)
44 self
45 end
46 end
47 end