Sha256: 1d079b2132dbddbb4aae3b59122aba3f0faa52f6144010000e64565b0d8dd5a9

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

require 'rockit/tree/base'

class Object
  def to_graphviz_node_label; inspect; end
  def to_graphviz_printer(printer); printer; end
end

class Array
  def to_graphviz_node_label; "[]"; end
  def to_graphviz_printer(printer)
    label = printer.unique(self)
    each do |child|
      printer.add(label, child)
      child.to_graphviz_printer(printer)
    end
    printer
  end
end

class DotPrinter
  def initialize
    @links = []
    @counts = Hash.new(0)
  end

  def unique(obj)
    num = (@counts[obj.class] += 1)
    obj.to_graphviz_node_label + " (#{num})"
  end

  def add(from, to)
    @links << [from.to_graphviz_node_label, to.to_graphviz_node_label]
  end

  def to_dot_file
    "digraph {" +
      @links.uniq.map {|from, to| "#{from.inspect} -> #{to.inspect};"}.join("\n") +
      "}"
  end

  def write_to_file(filename, format = "ps")
    tmpfilename = "temp" + Time.now.strftime("%M%S_") + rand(1e10).inspect
    File.open(tmpfilename, "w") do |fh|
      fh.write self.to_dot_file
      system "dot -T#{format} #{tmpfilename} > #{filename}"
    end
    # File.delete(tmpfilename)
  end
end

module Rockit::Tree
  class Base
    def to_graphviz_printer(printer = DotPrinter.new)
      children.each do |child|
	printer.add(self, child)
	child.to_graphviz_printer(printer)
      end
      printer
    end

    def to_graphviz_node_label
      class_name_as_string
    end

    def class_name_as_string
      self.class.inspect.split("::").last
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rockit-0.7.1 lib/rockit/tree/graphviz.rb