bguthrie (owner)

Revisions

  • acce33 Sat Jan 31 15:28:17 -0800 2009
gist: 55706 Download_button fork
public
Description:
A patch for ActiveResource that allows it to use LibXML to parse documents. Use to speed up ARes.
Public Clone URL: git://gist.github.com/55706.git
Embed All Files: show embed
libxml_active_resource.rb #
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
65
66
67
68
69
70
71
72
73
74
require 'libxml'
 
module LibXML
  module XML
    module Conversions
      module Document
        def to_hash
          root.to_hash
        end
      end
 
      module Node
        CONTENT_ROOT = '__content__'
 
        def to_hash(hash={})
          if text?
            hash[CONTENT_ROOT] = content
          else
            hash[name] = sub_hash = {}
            attributes_to_hash(sub_hash)
            if array?
              children_array_to_hash(sub_hash)
            else
              children_to_hash(sub_hash)
            end
          end
          hash
        end
 
        protected
 
        def children_to_hash(hash={})
          each { |child| child.to_hash(hash) }
          hash
        end
 
        def attributes_to_hash(hash={})
          each_attr { |attr| hash[attr.name] = attr.value }
          hash
        end
 
        def children_array_to_hash(hash={})
          hash[child.name] = map do |child|
            returning({}) { |sub_hash| child.children_to_hash(sub_hash) }
          end
          hash
        end
 
        def array?
          child? && child.next? && child.name == child.next.name
        end
      end
    end
  end
end
 
LibXML::XML::Document.send(:include, LibXML::XML::Conversions::Document)
LibXML::XML::Node.send(:include, LibXML::XML::Conversions::Node)
 
module ActiveSupport
  module CoreExtensions
    module Hash
      module Conversions
        module ClassMethods
          # libxml
          def from_xml(xml)
            xml.gsub!(/\s*\n\s*/, '')
            typecast_xml_value(undasherize_keys(LibXML::XML::Parser.string(xml).parse.to_hash))
          end
        end
      end
    end
  end
end