Sha256: 1325c16336e7a19dc048da28e8985a6a8ec92107c490fd0a9e0d5c2d5ae3964b

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

require 'delegate'
require 'pp'

module Tangle
  #
  # A named vertex in a graph
  #
  class Vertex < SimpleDelegator
    include PP::ObjectMixin

    # Create a new vertex
    #
    # Vertex.new(...) => Vertex
    #
    # Named arguments:
    #   graph: a Graph or nil for an orphaned vertex
    #   name: anything that's hashable and unique within the graph
    #   delegate: delegate object for missing methods
    #
    def initialize(graph: nil,
                   name: nil,
                   delegate: nil,
                   vertex_id: object_id)
      super(delegate) unless delegate.nil?

      @graph = graph
      @name = name
      @delegate = delegate
      @vertex_id = vertex_id
    end

    # Duplicate a vertex in a new graph, keeping all other contained attributes
    # End users should probably use Graph#subgrap instead.
    #
    # dup_into(new_graph) => Vertex
    #
    # Raises an ArgumentError if graph would remain the same.
    #
    def dup_into(graph)
      raise ArgumentError if graph == @graph

      Vertex.new(
        graph:     graph,
        name:      @name,
        delegate:  @delegate,
        vertex_id: @vertex_id
      )
    end

    # Return all edges that touch this vertex
    #
    def edges
      return [] if @graph.nil?

      @graph.edges { |edge| edge.include? self }
    end

    # If two vertices have the same vertex_id, they have the same value
    #
    def ==(other)
      @vertex_id == other.vertex_id
    end

    # If two vertices have the same vertex_id, they have the same value
    #
    def !=(other)
      @vertex_id != other.vertex_id
    end

    # If two vertices have the same object_id, they are identical
    #
    def eql?(other)
      @object_id == other.object_id
    end

    attr_reader :graph
    attr_reader :name
    attr_reader :delegate
    attr_reader :vertex_id
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tangle-0.2.1 lib/tangle/vertex.rb
tangle-0.2.0 lib/tangle/vertex.rb
tangle-0.1.0 lib/tangle/vertex.rb