Class: Smartgen::Indexer

Inherits:
Object
  • Object
show all
Defined in:
lib/smartgen/indexer.rb

Overview

Parses the given HTML contents and generates a structure of indexes based on h1, h2, h3, h4, h5, h6 tags.

It will also add IDs to each hx tag, based on their content and store this modified content on #result.

On #index it will store a hierarchical structure for the h tags it encounters, with title, id, level, numbered_index and chidren.

For example, this HTML:

<h2>My header</h2>
<h3>Some minor header</h3>
<h3>Another minor header</h3>
<h2>My other header</h2>
<h3>Some other minor header</h3>

Will generate this HTML using #result:

<h2 id="my-header">My header</h2>
<h3 id="some-minor-header">Some minor header</h3>
<h3 id="another-minor-header">Another minor header</h3>
<h2 id="my-other-header">My other header</h2>
<h3 id="some-other-minor-header">Some other minor header</h3>

And this structure in #index:

[{
  :level=>2,
  :text=>"My header",
  :id=>"my-header",
  :children=>
    [{:level=>3,
      :text=>"Some minor header",
      :children=>[],
      :id=>"some-minor-header"},
    {:level=>3,
      :text=>"Another minor header",
      :children=>[],
      :id=>"another-minor-header"}],
},
{
   :level=>2,
   :text=>"My other header",
   :id=>"my-other-header"
   :children=> [{:level=>3, :text=>"Some other minor header", :children=>[], :id=>"some-other-minor-header"}],
}]

If can pass :numbered_index => true in the options, and it will add a numbered index on each title and add a :numbered_index key with its value on each node in the hash generated by #index.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(contents, options = {}) ⇒ Indexer

Returns a new instance of Indexer.



58
59
60
61
62
63
64
65
# File 'lib/smartgen/indexer.rb', line 58

def initialize(contents, options={})
  @contents = contents
  @result = @contents.dup
  @options = options.is_a?(Hash) ? options : {}
  @index = []
  
  parse
end

Instance Attribute Details

#indexObject

Returns the value of attribute index.



56
57
58
# File 'lib/smartgen/indexer.rb', line 56

def index
  @index
end

#resultObject

Returns the value of attribute result.



56
57
58
# File 'lib/smartgen/indexer.rb', line 56

def result
  @result
end