class Madness::InlineTableOfContents
Generate a markdown Table of Contents for a single document
Attributes
Public Class Methods
Source
# File lib/madness/inline_table_of_contents.rb, line 9 def initialize(text) @text = text end
Public Instance Methods
Source
# File lib/madness/inline_table_of_contents.rb, line 13 def markdown @markdown ||= ([caption, ''] + items).join "\n" end
Protected Instance Methods
Source
# File lib/madness/inline_table_of_contents.rb, line 44 def caption @caption ||= config.auto_toc.is_a?(String) ? config.auto_toc : '## Table of Contents' end
Source
# File lib/madness/inline_table_of_contents.rb, line 23 def headers @headers ||= text.lines(chomp: true).select do |line| next if inside_code_block? line line.match(/^(?<level>\#{2,3})\s+(?<text>.+)/) end end
Source
# File lib/madness/inline_table_of_contents.rb, line 48 def inside_code_block?(line) @marker ||= false if !@marker && line.start_with?('```') @marker = line[/^`{3,4}/] elsif @marker && line.start_with?(@marker) @marker = false end !!@marker end
Source
# File lib/madness/inline_table_of_contents.rb, line 19 def items @items ||= headers.map { |line| toc_item line } end
Source
# File lib/madness/inline_table_of_contents.rb, line 31 def toc_item(line) matches = line.match(/^(?<level>\#{2,3})\s+(?<text>.+)/) return nil unless matches text = matches[:text] level = matches[:level].size - 2 spacer = ' ' * level slug = text.to_slug config.renderer "#{spacer}- [#{text}](##{slug})" end