File: active_support/core_ext/hash/conversions.rb

Overview
Module Structure
Code

Overview

Module Structure

  module: <Toplevel Module>
  module: ActiveSupport#4
  module: CoreExtensions#12
  module: Hash#13
  module: Conversions#14
has properties
constant: XML_TYPE_NAMES #29
constant: XML_FORMATTING #43
constant: XML_PARSING #54
module method: included / 1 #80
method: to_query / 1 #91
method: to_xml / 1 #99
method: rename_key / 2 #154
  module: FileLike#17
has properties
attribute: original_filename (1/2) [W] #18
attribute: content_type (1/2) [W] #18
method: original_filename (2/E) #20
method: content_type (2/E) #24
  module: ClassMethods#162
has properties
method: from_xml / 1 #163
method: typecast_xml_value / 1 #168
method: unrename_keys / 1 #230

Code

   1  require 'date'
   2  require 'active_support/core_ext/module/attribute_accessors'
   3 
   4  module ActiveSupport #:nodoc:
   5    # these accessors are here because people using ActiveResource and REST to integrate with other systems
   6    # have to be able to control the default behavior of rename_key. dasherize_xml is set to true to emulate
   7    # existing behavior. In a future version it should be set to false by default.
   8    mattr_accessor :dasherize_xml
   9    mattr_accessor :camelize_xml
  10    self.dasherize_xml = true
  11    self.camelize_xml  = false
  12    module CoreExtensions #:nodoc:
  13      module Hash #:nodoc:
  14        module Conversions
  15          # This module exists to decorate files deserialized using Hash.from_xml with
  16          # the <tt>original_filename</tt> and <tt>content_type</tt> methods.
  17          module FileLike #:nodoc:
  18            attr_writer :original_filename, :content_type
  19 
  20            def original_filename
  21              @original_filename || 'untitled'
  22            end
  23 
  24            def content_type
  25              @content_type || 'application/octet-stream'
  26            end
  27          end
  28 
  29          XML_TYPE_NAMES = {
  30            "Symbol"     => "symbol",
  31            "Fixnum"     => "integer",
  32            "Bignum"     => "integer",
  33            "BigDecimal" => "decimal",
  34            "Float"      => "float",
  35            "TrueClass"  => "boolean",
  36            "FalseClass" => "boolean",
  37            "Date"       => "date",
  38            "DateTime"   => "datetime",
  39            "Time"       => "datetime",
  40            "ActiveSupport::TimeWithZone" => "datetime"
  41          } unless defined?(XML_TYPE_NAMES)
  42 
  43          XML_FORMATTING = {
  44            "symbol"   => Proc.new { |symbol| symbol.to_s },
  45            "date"     => Proc.new { |date| date.to_s(:db) },
  46            "datetime" => Proc.new { |time| time.xmlschema },
  47            "binary"   => Proc.new { |binary| ActiveSupport::Base64.encode64(binary) },
  48            "yaml"     => Proc.new { |yaml| yaml.to_yaml }
  49          } unless defined?(XML_FORMATTING)
  50 
  51          # TODO: use Time.xmlschema instead of Time.parse;
  52          #       use regexp instead of Date.parse
  53          unless defined?(XML_PARSING)
  54            XML_PARSING = {
  55              "symbol"       => Proc.new  { |symbol|  symbol.to_sym },
  56              "date"         => Proc.new  { |date|    ::Date.parse(date) },
  57              "datetime"     => Proc.new  { |time|    ::Time.parse(time).utc rescue ::DateTime.parse(time).utc },
  58              "integer"      => Proc.new  { |integer| integer.to_i },
  59              "float"        => Proc.new  { |float|   float.to_f },
  60              "decimal"      => Proc.new  { |number|  BigDecimal(number) },
  61              "boolean"      => Proc.new  { |boolean| %w(1 true).include?(boolean.strip) },
  62              "string"       => Proc.new  { |string|  string.to_s },
  63              "yaml"         => Proc.new  { |yaml|    YAML::load(yaml) rescue yaml },
  64              "base64Binary" => Proc.new  { |bin|     ActiveSupport::Base64.decode64(bin) },
  65              "file"         => Proc.new do |file, entity|
  66                f = StringIO.new(ActiveSupport::Base64.decode64(file))
  67                f.extend(FileLike)
  68                f.original_filename = entity['name']
  69                f.content_type = entity['content_type']
  70                f
  71              end
  72            }
  73 
  74            XML_PARSING.update(
  75              "double"   => XML_PARSING["float"],
  76              "dateTime" => XML_PARSING["datetime"]
  77            )
  78          end
  79 
  80          def self.included(klass)
  81            klass.extend(ClassMethods)
  82          end
  83 
  84          # Converts a hash into a string suitable for use as a URL query string. An optional <tt>namespace</tt> can be
  85          # passed to enclose the param names (see example below).
  86          #
  87          # ==== Examples
  88          #   { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish"
  89          #
  90          #   { :name => 'David', :nationality => 'Danish' }.to_query('user') # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
  91          def to_query(namespace = nil)
  92            collect do |key, value|
  93              value.to_query(namespace ? "#{namespace}[#{key}]" : key)
  94            end.sort * '&'
  95          end
  96          
  97          alias_method :to_param, :to_query
  98 
  99          def to_xml(options = {})
 100            require 'builder' unless defined?(Builder)
 101 
 102            options = options.dup
 103            options[:indent] ||= 2
 104            options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]),
 105                                     :root => "hash" })
 106            options[:builder].instruct! unless options.delete(:skip_instruct)
 107            root = rename_key(options[:root].to_s, options)
 108 
 109            options[:builder].__send__(:method_missing, root) do
 110              each do |key, value|
 111                case value
 112                  when ::Hash
 113                    value.to_xml(options.merge({ :root => key, :skip_instruct => true }))
 114                  when ::Array
 115                    value.to_xml(options.merge({ :root => key, :children => key.to_s.singularize, :skip_instruct => true}))
 116                  when ::Method, ::Proc
 117                    # If the Method or Proc takes two arguments, then
 118                    # pass the suggested child element name.  This is
 119                    # used if the Method or Proc will be operating over
 120                    # multiple records and needs to create an containing
 121                    # element that will contain the objects being
 122                    # serialized.
 123                    if 1 == value.arity
 124                      value.call(options.merge({ :root => key, :skip_instruct => true }))
 125                    else
 126                      value.call(options.merge({ :root => key, :skip_instruct => true }), key.to_s.singularize)
 127                    end
 128                  else
 129                    if value.respond_to?(:to_xml)
 130                      value.to_xml(options.merge({ :root => key, :skip_instruct => true }))
 131                    else
 132                      type_name = XML_TYPE_NAMES[value.class.name]
 133 
 134                      key = rename_key(key.to_s, options)
 135 
 136                      attributes = options[:skip_types] || value.nil? || type_name.nil? ? { } : { :type => type_name }
 137                      if value.nil?
 138                        attributes[:nil] = true
 139                      end
 140 
 141                      options[:builder].tag!(key,
 142                        XML_FORMATTING[type_name] ? XML_FORMATTING[type_name].call(value) : value,
 143                        attributes
 144                      )
 145                    end
 146                end
 147              end
 148              
 149              yield options[:builder] if block_given?
 150            end
 151 
 152          end
 153 
 154          def rename_key(key, options = {})
 155            camelize  = options.has_key?(:camelize) ? options[:camelize]   : ActiveSupport.camelize_xml
 156            dasherize = options.has_key?(:dasherize) ? options[:dasherize] : ActiveSupport.dasherize_xml
 157            key = key.camelize if camelize
 158            key = key.dasherize if dasherize
 159            key
 160          end
 161 
 162          module ClassMethods
 163            def from_xml(xml)
 164              typecast_xml_value(unrename_keys(XmlMini.parse(xml)))
 165            end
 166 
 167            private
 168              def typecast_xml_value(value)
 169                case value.class.to_s
 170                  when 'Hash'
 171                    if value['type'] == 'array'
 172                      child_key, entries = value.detect { |k,v| k != 'type' }   # child_key is throwaway
 173                      if entries.nil? || (c = value['__content__'] && c.blank?)
 174                        []
 175                      else
 176                        case entries.class.to_s   # something weird with classes not matching here.  maybe singleton methods breaking is_a?
 177                        when "Array"
 178                          entries.collect { |v| typecast_xml_value(v) }
 179                        when "Hash"
 180                          [typecast_xml_value(entries)]
 181                        else
 182                          raise "can't typecast #{entries.inspect}"
 183                        end
 184                      end
 185                    elsif value.has_key?("__content__")
 186                      content = value["__content__"]
 187                      if parser = XML_PARSING[value["type"]]
 188                        if parser.arity == 2
 189                          XML_PARSING[value["type"]].call(content, value)
 190                        else
 191                          XML_PARSING[value["type"]].call(content)
 192                        end
 193                      else
 194                        content
 195                      end
 196                    elsif value['type'] == 'string' && value['nil'] != 'true'
 197                      ""
 198                    # blank or nil parsed values are represented by nil
 199                    elsif value.blank? || value['nil'] == 'true'
 200                      nil
 201                    # If the type is the only element which makes it then 
 202                    # this still makes the value nil, except if type is
 203                    # a XML node(where type['value'] is a Hash)
 204                    elsif value['type'] && value.size == 1 && !value['type'].is_a?(::Hash)
 205                      nil
 206                    else
 207                      xml_value = value.inject({}) do |h,(k,v)|
 208                        h[k] = typecast_xml_value(v)
 209                        h
 210                      end
 211                      
 212                      # Turn { :files => { :file => #<StringIO> } into { :files => #<StringIO> } so it is compatible with
 213                      # how multipart uploaded files from HTML appear
 214                      xml_value["file"].is_a?(StringIO) ? xml_value["file"] : xml_value
 215                    end
 216                  when 'Array'
 217                    value.map! { |i| typecast_xml_value(i) }
 218                    case value.length
 219                      when 0 then nil
 220                      when 1 then value.first
 221                      else value
 222                    end
 223                  when 'String'
 224                    value
 225                  else
 226                    raise "can't typecast #{value.class.name} - #{value.inspect}"
 227                end
 228              end
 229 
 230              def unrename_keys(params)
 231                case params.class.to_s
 232                  when "Hash"
 233                    params.inject({}) do |h,(k,v)|
 234                      h[k.to_s.tr("-", "_")] = unrename_keys(v)
 235                      h
 236                    end
 237                  when "Array"
 238                    params.map { |v| unrename_keys(v) }
 239                  else
 240                    params
 241                end
 242              end
 243          end
 244        end
 245      end
 246    end
 247  end