Skip to content

Instantly share code, notes, and snippets.

@maccman
Created January 5, 2009 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maccman/43449 to your computer and use it in GitHub Desktop.
Save maccman/43449 to your computer and use it in GitHub Desktop.
# Advanced to_xml
#
# Alex MacCaw
# info@eribium.org
#
# Provide to_xml support to things like strings,
# so you can now actually do ['foo'].to_xml without
# it throwing an exception.
#
# One gotcha to look out for is Rails calls
# to_xml in the render method, so:
#
# render :xml => {:foo => 'bar'}.to_xml(:title => 'widget')
#
# produces:
#
# <?xml version="1.0" encoding="UTF-8"?>
# <string>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
# &lt;hash&gt;
# &lt;foo&gt;bar&lt;/foo&gt;
# &lt;/hash&gt;
# </string>
#
# The solution is to bypass Rails' magic:
#
# render :text => {:foo => 'bar'}.to_xml(:title => 'widget'),
# :content_type => Mime::XML
#
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module SimpleType
def to_xml(options = {})
options[:indent] ||= 2
options.reverse_merge!({ :builder => Builder::XmlMarkup.new(:indent => options[:indent]),
:root => self.class.to_s.underscore })
options[:builder].instruct! unless options.delete(:skip_instruct)
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
root = dasherize ? options[:root].to_s.dasherize : options[:root].to_s
type_name = Hash::Conversions::XML_TYPE_NAMES[self.class.name]
attributes = options[:skip_types] || self.nil? || type_name.nil? ? { } : { :type => type_name }
if self.nil?
attributes[:nil] = true
end
options[:builder].tag!(root,
Hash::Conversions::XML_FORMATTING[type_name] ? Hash::Conversions::XML_FORMATTING[type_name].call(self) : self,
attributes
)
end
end
end
end
[NilClass, String, Numeric, Date, Time, TrueClass, FalseClass].each do |cls|
cls.class_eval do
include ActiveSupport::CoreExtensions::SimpleType
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment