diff options
author | Neeraj Singh <neerajdotname@gmail.com> | 2010-04-27 16:45:26 -0400 |
---|---|---|
committer | José Valim <jose.valim@gmail.com> | 2010-04-29 09:04:34 +0200 |
commit | 580dd3b052e471aa680b80c0e1d8ebe7bd7a3831 (patch) | |
tree | 4e10d448aff1b744346cccf62ce08a793de2d931 /activesupport/lib/active_support/core_ext/hash/conversions_xml_value.rb | |
parent | 1b816d502444ce2b3153d8c689d0057f1c257eee (diff) | |
download | rails-580dd3b052e471aa680b80c0e1d8ebe7bd7a3831.tar.gz rails-580dd3b052e471aa680b80c0e1d8ebe7bd7a3831.tar.bz2 rails-580dd3b052e471aa680b80c0e1d8ebe7bd7a3831.zip |
array.to_xml should be able to handle all types of data elements [#4490 state:resolved]
Signed-off-by: José Valim <jose.valim@gmail.com>
Diffstat (limited to 'activesupport/lib/active_support/core_ext/hash/conversions_xml_value.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/hash/conversions_xml_value.rb | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions_xml_value.rb b/activesupport/lib/active_support/core_ext/hash/conversions_xml_value.rb new file mode 100644 index 0000000000..fac8f90122 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/hash/conversions_xml_value.rb @@ -0,0 +1,51 @@ +class Hash + module XmlValue + def xml_value(key, value, options) + case value + 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})) + when ::Method, ::Proc + # If the Method or Proc takes two arguments, then + # pass the suggested child element name. This is + # used if the Method or Proc will be operating over + # multiple records and needs to create an containing + # element that will contain the objects being + # serialized. + if 1 == value.arity + value.call(options.merge({ :root => key, :skip_instruct => true })) + else + value.call(options.merge({ :root => key, :skip_instruct => true }), key.to_s.singularize) + end + else + if value.respond_to?(:to_xml) + value.to_xml(options.merge({ :root => key, :skip_instruct => true })) + else + type_name = XML_TYPE_NAMES[value.class.name] + + key = rename_key(key.to_s, options) + + attributes = options[:skip_types] || value.nil? || type_name.nil? ? { } : { :type => type_name } + if value.nil? + attributes[:nil] = true + end + + options[:builder].tag!(key, + XML_FORMATTING[type_name] ? XML_FORMATTING[type_name].call(value) : value, + attributes + ) + end + end + #yield options[:builder] if block_given? + end + + def rename_key(key, options = {}) + camelize = options.has_key?(:camelize) && options[:camelize] + dasherize = !options.has_key?(:dasherize) || options[:dasherize] + key = key.camelize if camelize + dasherize ? key.dasherize : key + end + end +end + |