Class: EPUB::Searcher::XHTML::Seamless

Inherits:
EPUB::Searcher::XHTML show all
Defined in:
lib/epub/searcher/xhtml.rb

Constant Summary

Constants inherited from EPUB::Searcher::XHTML

ALGORITHMS

Instance Method Summary collapse

Methods inherited from EPUB::Searcher::XHTML

search

Constructor Details

#initialize(element) ⇒ Seamless

Returns a new instance of Seamless.



60
61
62
63
# File 'lib/epub/searcher/xhtml.rb', line 60

def initialize(element)
  super
  @indices = nil
end

Instance Method Details

#build_indices(element) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/epub/searcher/xhtml.rb', line 72

def build_indices(element)
  indices = {}
  content = ''

  elem_index = 0
  element.children.each do |child|
    if child.element?
      child_step = [:element, elem_index, {:name => child.name, :id => Parser::Utils.extract_attribute(child, 'id')}]
      elem_index += 1
      if child.name == 'img'
        alt = Parser::Utils.extract_attribute(child, 'alt')
        next if alt.nil? || alt.empty?
        indices[content.length] = [child_step]
        content << alt
      else
        # TODO: Consider block level elements
        content_length = content.length
        sub_indices, sub_content = build_indices(child)
        sub_indices.each_pair do |sub_pos, child_steps|
          indices[content_length + sub_pos] = [child_step] + child_steps
        end
        content << sub_content
      end
    elsif child.text? || child.cdata?
      text_index = elem_index
      text_step = [:text, text_index]
      indices[content.length] = [text_step]
      content << child.content
    end
  end

  [indices, content]
end

#search(word) ⇒ Object



65
66
67
68
69
70
# File 'lib/epub/searcher/xhtml.rb', line 65

def search(word)
  unless @indices
    @indices, @content = build_indices(@element)
  end
  visit(@indices, @content, word)
end