class GovukTechDocs::TableOfContents::HeadingTreeBuilder

Public Class Methods

new(headings) click to toggle source
# File lib/govuk_tech_docs/table_of_contents/heading_tree_builder.rb, line 4
def initialize(headings)
  @headings = headings
  @tree = HeadingTree.new
  @pointer = @tree
end

Public Instance Methods

tree() click to toggle source
# File lib/govuk_tech_docs/table_of_contents/heading_tree_builder.rb, line 10
def tree
  @headings.each do |heading|
    move_to_depth(heading.size)

    @pointer.children << HeadingTree.new(parent: @pointer, heading: heading)
  end

  @tree
end

Private Instance Methods

move_to_depth(depth) click to toggle source
# File lib/govuk_tech_docs/table_of_contents/heading_tree_builder.rb, line 22
def move_to_depth(depth)
  if depth > @pointer.depth
    @pointer = @pointer.children.last

    if depth > @pointer.depth
      @pointer.children << HeadingTree.new(parent: @pointer)

      move_to_depth(depth)
    end
  end

  if depth < @pointer.depth
    @pointer = @pointer.parent

    move_to_depth(depth)
  end
end