Class: HTML::Pipeline::TableOfContentsFilter
- Defined in:
- lib/html/pipeline/toc_filter.rb
Overview
HTML filter that adds a ‘name’ attribute to all headers in a document, so they can be accessed from a table of contents
TODO: besides adding the name attribute, we should get around to eventually generating the Table of Contents itself, with links to each header
Constant Summary collapse
- PUNCTUATION_REGEXP =
RUBY_VERSION > "1.9" ? /[^\p{Word}\- ]/u : /[^\w\- ]/
Instance Attribute Summary
Attributes inherited from Filter
Instance Method Summary collapse
Methods inherited from Filter
#base_url, call, #current_user, #doc, #has_ancestor?, #html, #initialize, #needs, #parse_html, #repository, to_document, to_html, #validate
Constructor Details
This class inherits a constructor from HTML::Pipeline::Filter
Instance Method Details
#call ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/html/pipeline/toc_filter.rb', line 12 def call headers = Hash.new(0) doc.css('h1, h2, h3, h4, h5, h6').each do |node| name = node.text.downcase name.gsub!(PUNCTUATION_REGEXP, '') # remove punctuation name.gsub!(' ', '-') # replace spaces with dash uniq = (headers[name] > 0) ? "-#{headers[name]}" : '' headers[name] += 1 if header_content = node.children.first header_content.add_previous_sibling(%Q{<a name="#{name}#{uniq}" class="anchor" href="##{name}#{uniq}"><span class="octicon octicon-link"></span></a>}) end end doc end |