Class: Yandex::Webmaster::Response::Hashify

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/yandex-webmaster/response/hashify.rb

Instance Method Summary collapse

Instance Method Details

#from_xml(xml, strict = true) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/yandex-webmaster/response/hashify.rb', line 13

def from_xml(xml, strict = true) 
  begin
    XML.default_load_external_dtd = false
    XML.default_pedantic_parser = strict
    result = XML::Parser.string(xml).parse 
    return xml_node_to_hash(result.root)
  rescue Exception => e
    # raise custom exception here      
  end 
end

#parse(body) ⇒ Object



9
10
11
# File 'lib/yandex-webmaster/response/hashify.rb', line 9

def parse(body)      
  self.from_xml(body) if body.present?
end

#xml_node_to_hash(node) ⇒ Object



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
# File 'lib/yandex-webmaster/response/hashify.rb', line 24

def xml_node_to_hash(node)             
  if node.element? 
    if node.children? || node.attributes?
      result_hash = {} 

      node.each_child do |child| 
        result = xml_node_to_hash(child) 

        if child.name == "text"
          return result if !child.next? && !child.prev? && result.present?              
        elsif result_hash[child.name.underscore.to_sym] && result.present?
          if result_hash[child.name.underscore.to_sym].is_a?(Object::Array)
            result_hash[child.name.underscore.to_sym] << result
          else
            result_hash[child.name.underscore.to_sym] = [result_hash[child.name.underscore.to_sym]] << result
          end
        elsif result.present?
          result_hash[child.name.underscore.to_sym] = result
        end
      end

      node.each_attr do |attr|
        result_hash[attr.name.underscore.to_sym] = attr.value
      end

      return result_hash 
    else 
      return nil 
    end 
  else 
    return node.content.to_s 
  end 
end