Class: ASpaceExport::StreamHandler

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

Instance Method Summary (collapse)

Constructor Details

- (StreamHandler) initialize

Returns a new instance of StreamHandler



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

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

Instance Method Details

- (Object) buffer(&block)



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

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

- (Object) stream_out(doc, fragments, y, depth = 0)



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

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.parse ""
    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