2
require 'active_support/core_ext/module/attribute_accessors'
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:
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
21
@original_filename || 'untitled'
25
@content_type || 'application/octet-stream'
31
"Fixnum" => "integer",
32
"Bignum" => "integer",
33
"BigDecimal" => "decimal",
35
"TrueClass" => "boolean",
36
"FalseClass" => "boolean",
38
"DateTime" => "datetime",
40
"ActiveSupport::TimeWithZone" => "datetime"
41
} unless defined?(XML_TYPE_NAMES)
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)
51
# TODO: use Time.xmlschema instead of Time.parse;
52
# use regexp instead of Date.parse
53
unless defined?(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))
68
f.original_filename = entity['name']
69
f.content_type = entity['content_type']
75
"double" => XML_PARSING["float"],
76
"dateTime" => XML_PARSING["datetime"]
80
def self.included(klass)
81
klass.extend(ClassMethods)
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).
88
# { :name => 'David', :nationality => 'Danish' }.to_query # => "name=David&nationality=Danish"
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)
97
alias_method :to_param, :to_query
99
def to_xml(options = {})
100
require 'builder' unless defined?(Builder)
102
options = options.dup
103
options[:indent] ||= 2
104
options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]),
106
options[:builder].instruct! unless options.delete(:skip_instruct)
107
root = rename_key(options[:root].to_s, options)
109
options[:builder].__send__(:method_missing, root) do
113
value.to_xml(options.merge({ :root => key, :skip_instruct => true }))
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
124
value.call(options.merge({ :root => key, :skip_instruct => true }))
126
value.call(options.merge({ :root => key, :skip_instruct => true }), key.to_s.singularize)
129
if value.respond_to?(:to_xml)
130
value.to_xml(options.merge({ :root => key, :skip_instruct => true }))
132
type_name = XML_TYPE_NAMES[value.class.name]
134
key = rename_key(key.to_s, options)
136
attributes = options[:skip_types] || value.nil? || type_name.nil? ? { } : { :type => type_name }
138
attributes[:nil] = true
141
options[:builder].tag!(key,
142
XML_FORMATTING[type_name] ? XML_FORMATTING[type_name].call(value) : value,
149
yield options[:builder] if block_given?
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
164
typecast_xml_value(unrename_keys(XmlMini.parse(xml)))
168
def typecast_xml_value(value)
169
case value.class.to_s
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?)
176
case entries.class.to_s # something weird with classes not matching here. maybe singleton methods breaking is_a?
178
entries.collect { |v| typecast_xml_value(v) }
180
[typecast_xml_value(entries)]
182
raise "can't typecast #{entries.inspect}"
185
elsif value.has_key?("__content__")
186
content = value["__content__"]
187
if parser = XML_PARSING[value["type"]]
189
XML_PARSING[value["type"]].call(content, value)
191
XML_PARSING[value["type"]].call(content)
196
elsif value['type'] == 'string' && value['nil'] != 'true'
198
# blank or nil parsed values are represented by nil
199
elsif value.blank? || value['nil'] == 'true'
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)
207
xml_value = value.inject({}) do |h,(k,v)|
208
h[k] = typecast_xml_value(v)
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
217
value.map! { |i| typecast_xml_value(i) }
220
when 1 then value.first
226
raise "can't typecast #{value.class.name} - #{value.inspect}"
230
def unrename_keys(params)
231
case params.class.to_s
233
params.inject({}) do |h,(k,v)|
234
h[k.to_s.tr("-", "_")] = unrename_keys(v)
238
params.map { |v| unrename_keys(v) }