X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=lib%2Fgraph.njae%2Fedge.rb;h=7fd99b771bec5082e96f6fe2ebef7e11e283814c;hb=HEAD;hp=6581033d2a885bbe4fe8beddf1eddfb38879b50a;hpb=c34def40508c16cfc815fa02c8743d071491af7b;p=graph.njae.git diff --git a/lib/graph.njae/edge.rb b/lib/graph.njae/edge.rb index 6581033..7fd99b7 100644 --- a/lib/graph.njae/edge.rb +++ b/lib/graph.njae/edge.rb @@ -1,5 +1,3 @@ -require 'ostruct' - # A simple graph library module GraphNjae @@ -10,8 +8,8 @@ module GraphNjae # Each connection is handled by a Graph::Connection object, so that each end # of the Edge can have it's own attributes. class Edge < OpenStruct - def initialize - super + def initialize(values = {}) + super(values) self.connections = [] self end @@ -20,6 +18,7 @@ module GraphNjae def <<(other) c = Connection.new c.end = other + other.edges << self unless other.edges.include? self self.connections << c self end @@ -31,15 +30,46 @@ module GraphNjae # Return the connection object that joins this Edge to the specified Vertex def connection_at(vertex) - self.connections.select {|c| c.end.equal? vertex}.first + self.connections.find {|c| c.end.equal? vertex} + end + + # Return the vertex at the other end of the one given. + # Self-loops should still return the vertex + def other_end(vertex) + if self.vertices[0] == vertex + self.vertices[1] + else + self.vertices[0] + end + end + + def to_s + '' + end + + def to_dot(opts = {}) + if block_given? + yield self + else + dot = self.connections[0].end.object_id.to_s + " -- " + self.connections[1].end.object_id.to_s + if opts.size > 0 + dot << ' {' + dot << opts.keys.map { |k| + (k.to_s + ' = "' + self.instance_eval(opts[k].to_s).to_s) + '"' + }.join(', ') + dot << '}' + end + dot << ';' + end end + end # A connection between an Edge and a Vertex.The connection can have arbitrary attributes, # treated as method names. class Connection < OpenStruct - def initialize - super + def initialize(values = {}) + super(values) self end end