Added a :camelize option to ActiveRecord and Hash to_xml serialization and from_xml deserialization

Signed-off-by: Michael Koziarski <michael@koziarski.com>
This commit is contained in:
Bruce Krysiak
2008-12-08 16:38:04 -08:00
committed by Michael Koziarski
parent 96b815d7e8
commit aa5cdb0d47
4 changed files with 43 additions and 14 deletions

View File

@@ -23,11 +23,12 @@ module ActiveRecord #:nodoc:
# </topic>
#
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt> and <tt>:dasherize</tt>.
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
# +attributes+ method. The default is to dasherize all column names, but you
# can disable this setting <tt>:dasherize</tt> to +false+. To not have the
# column type included in the XML output set <tt>:skip_types</tt> to +true+.
# can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
# to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
# To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
#
# For instance:
#
@@ -178,13 +179,22 @@ module ActiveRecord #:nodoc:
def root
root = (options[:root] || @record.class.to_s.underscore).to_s
dasherize? ? root.dasherize : root
reformat_name(root)
end
def dasherize?
!options.has_key?(:dasherize) || options[:dasherize]
end
def camelize?
options.has_key?(:camelize) && options[:camelize]
end
def reformat_name(name)
name = name.camelize if camelize?
dasherize? ? name.dasherize : name
end
def serializable_attributes
serializable_attribute_names.collect { |name| Attribute.new(name, @record) }
end
@@ -212,7 +222,7 @@ module ActiveRecord #:nodoc:
def add_tag(attribute)
builder.tag!(
dasherize? ? attribute.name.dasherize : attribute.name,
reformat_name(attribute.name),
attribute.value.to_s,
attribute.decorations(!options[:skip_types])
)
@@ -220,8 +230,7 @@ module ActiveRecord #:nodoc:
def add_associations(association, records, opts)
if records.is_a?(Enumerable)
tag = association.to_s
tag = tag.dasherize if dasherize?
tag = reformat_name(association.to_s)
if records.empty?
builder.tag!(tag, :type => :array)
else

View File

@@ -31,6 +31,13 @@ class XmlSerializationTest < ActiveRecord::TestCase
assert_match %r{<created_at}, @xml
end
def test_should_allow_camelized_tags
@xml = Contact.new.to_xml :root => 'xml_contact', :camelize => true
assert_match %r{^<XmlContact>}, @xml
assert_match %r{</XmlContact>$}, @xml
assert_match %r{<CreatedAt}, @xml
end
def test_should_include_yielded_additions
@xml = Contact.new.to_xml do |xml|
xml.creator "David"