File: to_hash_document.rb

package info (click to toggle)
ruby-fog-xml 0.1.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 192 kB
  • ctags: 39
  • sloc: ruby: 246; makefile: 2
file content (64 lines) | stat: -rw-r--r-- 1,725 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
64
module Fog
  class ToHashDocument < Nokogiri::XML::SAX::Document
    def initialize
      @stack = []
    end

    def characters(string)
      @value ||= ""
      @value << string.strip
    end

    def end_element(name)
      last = @stack.pop
      if last.empty? && @value.empty?
        @stack.last[name.to_sym] = ""
      elsif last == { :i_nil => "true" }
        @stack.last[name.to_sym] = nil
      elsif !@value.empty?
        @stack.last[name.to_sym] = @value
      end
      @value = ""
    end

    def body
      @stack.first
    end

    def response
      body
    end

    def start_element(name, attributes = [])
      @value = ""
      parsed_attributes = {}
      until attributes.empty?
        if attributes.first.is_a?(Array)
          key, value = attributes.shift
        else
          key, value = attributes.shift, attributes.shift
        end
        parsed_attributes[key.gsub(":", "_").to_sym] = value
      end
      if @stack.last.is_a?(Array)
        @stack.last << { name.to_sym => parsed_attributes }
      else
        data = if @stack.empty?
                 @stack.push(parsed_attributes)
                 parsed_attributes
               elsif @stack.last[name.to_sym]
                 unless @stack.last[name.to_sym].is_a?(Array)
                   @stack.last[name.to_sym] = [@stack.last[name.to_sym]]
                 end
                 @stack.last[name.to_sym] << parsed_attributes
                 @stack.last[name.to_sym].last
               else
                 @stack.last[name.to_sym] = {}
                 @stack.last[name.to_sym].merge!(parsed_attributes)
                 @stack.last[name.to_sym]
               end
        @stack.push(data)
      end
    end
  end
end