Class: Mullet::HTML::FilteredElementHandler

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Defined in:
lib/mullet/html/filtered_element_handler.rb

Overview

Proxy for a SAX event handler that forwards events only while the parser is within an element identified by an id attribute.

Constant Summary collapse

ID =
'id'

Instance Method Summary collapse

Constructor Details

#initialize(handler, id) ⇒ FilteredElementHandler

Constructor

Parameters:

  • handler (Document)

    event handler to forward events to

  • id (String)

    id attribute value



19
20
21
22
23
24
# File 'lib/mullet/html/filtered_element_handler.rb', line 19

def initialize(handler, id)
  @handler = handler
  @id = id
  @depth = 0
  @found_id = false
end

Instance Method Details

#cdata_block(data) ⇒ Object



74
75
76
77
78
# File 'lib/mullet/html/filtered_element_handler.rb', line 74

def cdata_block(data)
  if should_forward()
    @handler.cdata_block(data)
  end
end

#characters(data) ⇒ Object



68
69
70
71
72
# File 'lib/mullet/html/filtered_element_handler.rb', line 68

def characters(data)
  if should_forward()
    @handler.characters(data)
  end
end

#comment(data) ⇒ Object



80
81
82
83
84
# File 'lib/mullet/html/filtered_element_handler.rb', line 80

def comment(data)
  if should_forward()
    @handler.comment(data)
  end
end

#end_documentObject



34
35
36
37
38
39
40
# File 'lib/mullet/html/filtered_element_handler.rb', line 34

def end_document()
  @handler.end_document()

  if !@found_id
    raise TemplateError.new("element with attribute id='#{@id}' not found")
  end
end

#end_element_namespace(name, prefix, uri) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/mullet/html/filtered_element_handler.rb', line 59

def end_element_namespace(name, prefix, uri)
  if should_forward()
    @depth -= 1
    if @depth > 0
      @handler.end_element_namespace(name, prefix, uri)
    end
  end
end

#should_forwardObject



26
27
28
# File 'lib/mullet/html/filtered_element_handler.rb', line 26

def should_forward()
  return @depth > 0
end

#start_documentObject



30
31
32
# File 'lib/mullet/html/filtered_element_handler.rb', line 30

def start_document()
  @handler.start_document()
end

#start_element_namespace(name, attributes, prefix, uri, namespaces) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mullet/html/filtered_element_handler.rb', line 42

def start_element_namespace(name, attributes, prefix, uri, namespaces)
  if should_forward()
    @depth += 1
    return @handler.start_element_namespace(
        name, attributes, prefix, uri, namespaces)
  end

  value = attributes.each do |attr|
    qualified_name = [attr.prefix, attr.localname].compact.join(':')
    if qualified_name == ID && attr.value == @id
      # Enable event forwarding.
      @depth = 1
      @found_id = true
    end
  end
end