Class: ASpaceExport::StreamHandler

Inherits:
Object
  • Object
show all
Defined in:
backend/app/exporters/lib/streaming_xml.rb

Instance Method Summary collapse

Constructor Details

#initializeStreamHandler

Returns a new instance of StreamHandler.



26
27
28
29
# File 'backend/app/exporters/lib/streaming_xml.rb', line 26

def initialize
  @sections = {}
  @depth = 0
end

Instance Method Details

#buffer(&block) ⇒ Object



32
33
34
35
36
# File 'backend/app/exporters/lib/streaming_xml.rb', line 32

def buffer(&block)
  id = SecureRandom.hex
  @sections[id] = block
  ":aspace_section_#{id}_"
end

#stream_out(doc, fragments, y, depth = 0) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'backend/app/exporters/lib/streaming_xml.rb', line 38

def stream_out(doc, fragments, y, depth=0)
  xml_text = doc.to_xml(:encoding => 'utf-8')

  return if xml_text.empty?
  xml_text.force_encoding('utf-8')
  queue = xml_text.split(":aspace_section")

  xml_string = fragments.substitute_fragments(queue.shift)
  raise "Undereferenced Fragment: #{xml_string}" if xml_string =~ /:aspace_fragment/
  y << xml_string

  while queue.length > 0
    next_section = queue.shift
    next_id = next_section.slice!(/^_(\w+)_/).gsub(/_/, '')
    next_fragments = RawXMLHandler.new
    doc_frag = Nokogiri::XML::DocumentFragment.new(Nokogiri::XML::Document.new)
    Nokogiri::XML::Builder.with(doc_frag) do |xml|
      @sections[next_id].call(xml, next_fragments)
    end
    stream_out(doc_frag, next_fragments, y, depth + 1)

    if next_section && !next_section.empty?
      y << fragments.substitute_fragments(next_section)
    end
  end
end