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.



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

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.



95
96
97
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 95

def elements_processed
  @elements_processed
end

Instance Method Details

#cdata_block(string) ⇒ Object



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

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

#characters(string) ⇒ Object



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

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

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

#end_element(_name) ⇒ Object



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

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



105
106
107
108
109
110
# File 'lib/serialbench/serializers/xml/nokogiri_serializer.rb', line 105

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