class Tocer::Builder

Builds table of contents for a Markdown document.

Constants

CODE_BLOCK_PUNCTUATION

Attributes

code_block[RW]
comment_block[R]
transformer[R]
url_count[R]

Public Class Methods

new(comment_block: Elements::CommentBlock.new, transformer: Transformers::Finder.new) click to toggle source
# File lib/tocer/builder.rb, line 14
def initialize comment_block: Elements::CommentBlock.new, transformer: Transformers::Finder.new
  @comment_block = comment_block
  @transformer = transformer
  @url_count = Hash.new 0
  @code_block = false
end

Public Instance Methods

call(lines, label: CLI::Configuration::Loader.call.label) click to toggle source
# File lib/tocer/builder.rb, line 21
def call lines, label: CLI::Configuration::Loader.call.label
  return "" if headers(lines).empty?

  assemble(lines, label).join
end

Private Instance Methods

assemble(lines, label) click to toggle source
# File lib/tocer/builder.rb, line 32
def assemble lines, label
  [
    "#{comment_block.start_tag}\n\n",
    "#{label}\n\n",
    links(lines).join("\n"),
    "\n\n#{comment_block.finish_tag}\n"
  ]
end
headers(lines) click to toggle source
# File lib/tocer/builder.rb, line 43
def headers lines
  lines.select do |line|
    toggle_code_block line
    line.start_with?(Parsers::Header::PUNCTUATION) && !code_block
  end
end
toggle_code_block(line) click to toggle source
# File lib/tocer/builder.rb, line 50
def toggle_code_block line
  return unless line.start_with? CODE_BLOCK_PUNCTUATION

  self.code_block = !code_block
end
transform(markdown) click to toggle source
# File lib/tocer/builder.rb, line 56
def transform markdown
  transformer.call(markdown).then do |instance|
    url = instance.url
    link = instance.call url_suffix: url_suffix(url)
    url_count[url] += 1
    link
  end
end
url_suffix(url) click to toggle source
# File lib/tocer/builder.rb, line 65
  def url_suffix(url) = url_count[url].then { |count| count.zero? ? "" : count }
end