Created
January 5, 2009 16:08
-
-
Save maccman/43449 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Advanced to_xml | |
# | |
# Alex MacCaw | |
# [email protected] | |
# | |
# 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><?xml version="1.0" encoding="UTF-8"?> | |
# <hash> | |
# <foo>bar</foo> | |
# </hash> | |
# </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