class MiniGraph::DSL::GraphContext

Attributes

vertex_index[R]

Protected Methods


Public Class Methods

evaluate(*vertices, &block) click to toggle source
# File lib/mini_graph/dsl/graph_context.rb, line 7
def self.evaluate(*vertices, &block)
  unless block_given?
    raise ArgumentError, "cannot call .create without a block"
  end

  graph_context = new(vertices)
  graph_context.instance_eval(&block)
  graph_context.resolve
end
new(vertices) click to toggle source
# File lib/mini_graph/dsl/graph_context.rb, line 42
def initialize(vertices)
  @vertices     = [vertices].flatten
  @vertex_index = @vertices.map.with_index { |v, i| [v, i] }.to_h
  @directed     = false
  @edges        = []
end

Public Instance Methods

resolve() click to toggle source

Public Methods


# File lib/mini_graph/dsl/graph_context.rb, line 21
def resolve
  if @edges.any? { |edge| edge.any?(&:nil?) }
    raise MiniGraph::Core::Error::InvalidEdgeError,
          'One or more invalid edges were specified'
  end

  MiniGraph::Core::Graph.new(@vertices, directed: @directed).tap do |g|
    @edges.each do |edge|
      g.add_edge(*edge)
    end
  end
end

Protected Instance Methods

directed!() click to toggle source
# File lib/mini_graph/dsl/graph_context.rb, line 53
def directed!
  @directed = true
end
edge(from:, to:) click to toggle source
# File lib/mini_graph/dsl/graph_context.rb, line 57
def edge(from:, to:)
  from_indices  = vertices_to_indices(from)
  to_indices    = vertices_to_indices(to)

  @edges += from_indices.flat_map do |origin|
    to_indices.map do |destination|
      [origin, destination]
    end
  end
end
undirected!() click to toggle source
# File lib/mini_graph/dsl/graph_context.rb, line 49
def undirected!
  @directed = false
end

Private Instance Methods

vertices_to_indices(vertices) click to toggle source

Private Methods


# File lib/mini_graph/dsl/graph_context.rb, line 74
def vertices_to_indices(vertices)
  [vertices].flatten.map { |v| vertex_index[v] }
end