Class: Verku::TOC::HTML

Inherits:
Object
  • Object
show all
Defined in:
lib/verku/toc/html.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHTML

:nodoc:



44
45
46
47
# File 'lib/verku/toc/html.rb', line 44

def initialize # :nodoc:
  @toc = []
  @counters = {}
end

Instance Attribute Details

#attrsObject (readonly)

:nodoc:



10
11
12
# File 'lib/verku/toc/html.rb', line 10

def attrs
  @attrs
end

#bufferObject (readonly)

:nodoc:



9
10
11
# File 'lib/verku/toc/html.rb', line 9

def buffer
  @buffer
end

#contentObject

:nodoc:



11
12
13
# File 'lib/verku/toc/html.rb', line 11

def content
  @content
end

#tocObject (readonly)

Return the table of contents in hash format.



6
7
8
# File 'lib/verku/toc/html.rb', line 6

def toc
  @toc
end

Class Method Details

.generate(content) ⇒ Object

Traverse every title normalizing its content as a permalink.



36
37
38
39
40
41
42
# File 'lib/verku/toc/html.rb', line 36

def self.generate(content)
  content = normalize(content)
  listener = new
  listener.content = content
  Stream.new(content, listener).parse
  listener
end

.normalize(content) ⇒ Object

Traverse every title and add a id attribute. Return the modified content.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/verku/toc/html.rb', line 16

def self.normalize(content)
  counter = {}
  html = Nokogiri::HTML.parse(content)
  html.search("h1, h2, h3, h4, h5, h6").each do |tag|
    title = tag.inner_text
    permalink = title.to_permalink

    counter[permalink] ||= 0
    counter[permalink] += 1

    permalink = "#{permalink}-#{counter[permalink]}" if counter[permalink] > 1

    tag.set_attribute("id", permalink)
  end

  html.css("body").to_xhtml.gsub(/<body>(.*?)<\/body>/m, "\\1")
end

Instance Method Details

#tag(node) ⇒ Object

:nodoc:



49
50
51
52
53
54
55
# File 'lib/verku/toc/html.rb', line 49

def tag(node) # :nodoc:
  toc << {
    :level     => node.name.gsub(/[^\d]/, "").to_i,
    :text      => node.text,
    :permalink => node["id"]
  }
end

#to_hashObject

Return a hash with all normalized attributes.



59
60
61
62
63
64
65
# File 'lib/verku/toc/html.rb', line 59

def to_hash
  {
    :content => content,
    :html => to_html,
    :toc => toc
  }
end

#to_htmlObject

Return the table of contents in HTML format.



69
70
71
72
73
74
75
# File 'lib/verku/toc/html.rb', line 69

def to_html
  String.new.tap do |html|
    toc.each do |options|
      html << %[<div class="level#{options[:level]} #{options[:permalink]}"><a href="##{options[:permalink]}"><span>#{CGI.escape_html(options[:text])}</span></a></div>]
    end
  end
end