class GovukTechDocs::TableOfContents::HeadingTreeRenderer

Constants

DEFAULT_INDENTATION
DEFAULT_MAX_LEVEL
INDENTATION_INCREMENT

Public Class Methods

new(heading_tree, max_level: nil) click to toggle source
# File lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb, line 8
def initialize(heading_tree, max_level: nil)
  @heading_tree = heading_tree
  @max_level = max_level || DEFAULT_MAX_LEVEL
end

Public Instance Methods

html() click to toggle source
# File lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb, line 13
def html
  render_tree(@heading_tree, level: 0)
end

Private Instance Methods

render_tree(tree, indentation: DEFAULT_INDENTATION, level: nil) click to toggle source
# File lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb, line 19
def render_tree(tree, indentation: DEFAULT_INDENTATION, level: nil)
  output = ''

  if tree.heading
    output += indentation + %{<a href="#{tree.heading.href}">#{tree.heading.title}</a>\n}
  end

  if tree.children.any? && level < @max_level
    output += indentation + "<ul>\n"

    tree.children.each do |child|
      output += indentation + INDENTATION_INCREMENT + "<li>\n"
      output += render_tree(
        child,
        indentation: indentation + INDENTATION_INCREMENT * 2,
        level: level + 1
      )
      output += indentation + INDENTATION_INCREMENT + "</li>\n"
    end

    output += indentation + "</ul>\n"
  end

  output
end