Class: Jekyll::TableOfContents::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/table_of_contents/parser.rb

Constant Summary collapse

PUNCTUATION_REGEXP =
RUBY_VERSION > '1.9' ? /[^\p{Word}\- ]/u : /[^\w\- ]/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(html) ⇒ Parser

Returns a new instance of Parser.



8
9
10
11
# File 'lib/table_of_contents/parser.rb', line 8

def initialize(html)
  @doc = Nokogiri::HTML::DocumentFragment.parse(html)
  @entries = parse_content
end

Instance Attribute Details

#docObject (readonly)

Returns the value of attribute doc.



6
7
8
# File 'lib/table_of_contents/parser.rb', line 6

def doc
  @doc
end

Instance Method Details

#build_tocObject



13
14
15
16
17
18
19
20
21
# File 'lib/table_of_contents/parser.rb', line 13

def build_toc
  toc = %Q{<ul class="section-nav">\n}

  @entries.each do |entry|
    toc << %Q{<li class="toc-entry toc-#{entry[:node_name]}"><a href="##{entry[:id]}#{entry[:uniq]}">#{entry[:text]}</a></li>\n}
  end

  toc << '</ul>'
end

#inject_anchors_into_htmlObject



23
24
25
26
27
28
29
# File 'lib/table_of_contents/parser.rb', line 23

def inject_anchors_into_html
  @entries.each do |entry|
    entry[:content_node].add_previous_sibling(%Q{<a id="#{entry[:id]}#{entry[:uniq]}" class="anchor" href="##{entry[:id]}#{entry[:uniq]}" aria-hidden="true"><span class="octicon octicon-link"></span></a>})
  end

  @doc.inner_html
end

#tocObject



31
32
33
# File 'lib/table_of_contents/parser.rb', line 31

def toc
  build_toc + inject_anchors_into_html
end