~michaelforrest/use-case-mapper/trunk

« back to all changes in this revision

Viewing changes to vendor/rails/activesupport/lib/active_support/xml_mini/nokogiri.rb

  • Committer: Michael Forrest
  • Date: 2010-10-15 16:28:50 UTC
  • Revision ID: michael.forrest@canonical.com-20101015162850-tj2vchanv0kr0dun
refrozeĀ gems

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
require 'nokogiri'
 
2
 
 
3
# = XmlMini Nokogiri implementation
 
4
module ActiveSupport
 
5
  module XmlMini_Nokogiri #:nodoc:
 
6
    extend self
 
7
 
 
8
    # Parse an XML Document string into a simple hash using libxml / nokogiri.
 
9
    # string::
 
10
    #   XML Document string to parse
 
11
    def parse(string)
 
12
      if string.blank?
 
13
        {}
 
14
      else
 
15
        doc = Nokogiri::XML(string) { |cfg| cfg.noblanks }
 
16
        raise doc.errors.first if doc.errors.length > 0
 
17
        doc.to_hash
 
18
      end
 
19
    end
 
20
 
 
21
    module Conversions
 
22
      module Document
 
23
        def to_hash
 
24
          root.to_hash
 
25
        end
 
26
      end
 
27
 
 
28
      module Node
 
29
        CONTENT_ROOT = '__content__'
 
30
 
 
31
        # Convert XML document to hash
 
32
        #
 
33
        # hash::
 
34
        #   Hash to merge the converted element into.
 
35
        def to_hash(hash = {})
 
36
          attributes = attributes_as_hash
 
37
          if hash[name]
 
38
            hash[name] = [hash[name]].flatten
 
39
            hash[name] << attributes
 
40
          else
 
41
            hash[name] ||= attributes
 
42
          end
 
43
 
 
44
          children.each { |child|
 
45
            next if child.blank? && 'file' != self['type']
 
46
 
 
47
            if child.text? || child.cdata?
 
48
              (attributes[CONTENT_ROOT] ||= '') << child.content
 
49
              next
 
50
            end
 
51
 
 
52
            child.to_hash attributes
 
53
          }
 
54
 
 
55
          hash
 
56
        end
 
57
 
 
58
        def attributes_as_hash
 
59
          Hash[*(attribute_nodes.map { |node|
 
60
            [node.node_name, node.value]
 
61
          }.flatten)]
 
62
        end
 
63
      end
 
64
    end
 
65
 
 
66
    Nokogiri::XML::Document.send(:include, Conversions::Document)
 
67
    Nokogiri::XML::Node.send(:include, Conversions::Node)
 
68
  end
 
69
end