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.



111
112
113
114
115
116
117
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 111

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.



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

def elements_processed
  @elements_processed
end

Instance Method Details

#cdata_block(string) ⇒ Object



141
142
143
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 141

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

#characters(string) ⇒ Object



135
136
137
138
139
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 135

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

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

#end_element(_name) ⇒ Object



126
127
128
129
130
131
132
133
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 126

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



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

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