aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/hash/conversions.rb
blob: bbbda3698f5bd4ca806946ecf05f01f164cb66fd (plain) (blame)
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
module ActiveSupport #:nodoc:
  module CoreExtensions #:nodoc:
    module Hash #:nodoc:
      module Conversions
        XML_TYPE_NAMES = {
          "Fixnum"     => "integer",
          "Date"       => "date",
          "Time"       => "datetime",
          "TrueClass"  => "boolean",
          "FalseClass" => "boolean"
        }
        
        XML_FORMATTING = {
          "date"     => Proc.new { |date| date.to_s(:db) },
          "datetime" => Proc.new { |time| time.to_s(:db) }
        }
        
        def to_xml(options = {})
          options[:indent] ||= 2
          options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]), :root => "hash" })
          options[:builder].instruct! unless options.delete(:skip_instruct)

          options[:builder].__send__(options[:root]) do
            for key in keys
              value = self[key]

              case value.class.to_s # TODO: Figure out why I have to to_s the class to do comparisons in order for tests to run
                when "Hash"
                  value.to_xml(options.merge({ :root => key, :skip_instruct => true }))
                when "Array"
                  value.to_xml(options.merge({ :root => key, :children => key.to_s.singularize, :skip_instruct => true}))
                else
                  type_name = XML_TYPE_NAMES[value.class.to_s]

                  options[:builder].__send__(key.to_s.dasherize, 
                    XML_FORMATTING[type_name] ? XML_FORMATTING[type_name].call(value) : value,
                    options[:skip_types] || value.nil? || type_name.nil? ? { } : { :type => type_name }
                  )
              end
            end
          end
        end
      end
    end
  end
end