Class: Serialbench::Serializers::Xml::NokogiriSerializer::StreamingHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/serialbench/serializers/xml/nokogiri_serializer.rb

Overview

SAX handler for streaming

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ StreamingHandler

Returns a new instance of StreamingHandler.



101
102
103
104
105
106
107
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 101

def initialize(&block)
  require 'nokogiri'
  @block = block
  @elements_processed = 0
  @current_element = nil
  @element_stack = []
end

Instance Attribute Details

#elements_processedObject (readonly)

Returns the value of attribute elements_processed.



99
100
101
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 99

def elements_processed
  @elements_processed
end

Instance Method Details

#cdata_block(string) ⇒ Object



131
132
133
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 131

def cdata_block(string)
  @element_stack.last[:text] += string if @element_stack.any?
end

#characters(string) ⇒ Object



125
126
127
128
129
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 125

def characters(string)
  return if string.strip.empty?

  @element_stack.last[:text] += string if @element_stack.any?
end

#end_element(_name) ⇒ Object



116
117
118
119
120
121
122
123
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 116

def end_element(_name)
  element = @element_stack.pop
  if @element_stack.empty?
    @block&.call(element)
  else
    @element_stack.last[:children] << element
  end
end

#start_element(name, attributes = []) ⇒ Object



109
110
111
112
113
114
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 109

def start_element(name, attributes = [])
  @elements_processed += 1
  attrs = Hash[attributes]
  @current_element = { name: name, attributes: attrs, children: [], text: '' }
  @element_stack.push(@current_element)
end