Sha256: 53efe983cebcd693371e91a0bfb09fbbdb7174a05c22bf05aeef78fb49b42b91

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

require "tree_graph/version"

module TreeGraph

  def tree_graph
    TopDown.new(self).tree_graph
  end

  def tree_graph_bottom_up
    BottomUp.new(self).tree_graph
  end

  module Node

    attr_accessor :is_last
    attr_reader :raw_node, :parent

    def initialize raw_node, parent=nil
      @raw_node, @parent, @is_last = raw_node, parent, false
    end

    def children_nodes
      children = []
      raw_node.children_for_tree_graph.each do |c|
        children << self.class.new(c, self)
      end
      return children if children.empty?
      children.last.is_last = true
      children
    end

    def level
      [indent, branch, raw_node.label_for_tree_graph].join
    end

    def levels
      [level] + children_nodes.map(&:tree_graph)
    end

    def ancestors
      return [] unless parent
      parent.ancestors + [parent]
    end

    def indent
      ancestors.map do |a|
        unless a.parent
          ''
        else
          a.is_last ? '  ' : '│ '
        end
      end.join
    end

  end

  class TopDown
    include Node

    def tree_graph
      levels.join("\n")
    end

    def branch
      return '' unless parent
      is_last ? '└─' : '├─'
    end
  end

  class BottomUp
    include Node

    def tree_graph
      levels.reverse.join("\n")
    end

    def branch
      return '' unless parent
      is_last ? '┌─' : '├─'
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tree_graph-0.2.1 lib/tree_graph.rb