From 35c058e156a2a43775211cf1d992bd25b8256283 Mon Sep 17 00:00:00 2001 From: Emmanuel Nicolau Date: Wed, 26 Nov 2008 11:31:08 -0200 Subject: [PATCH] XmlSerializer with skip_nils option --- .../active_record/serializers/xml_serializer.rb | 8 +++++--- activerecord/test/cases/xml_serialization_test.rb | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb index d171b74..e6202cc 100644 --- a/activerecord/lib/active_record/serializers/xml_serializer.rb +++ b/activerecord/lib/active_record/serializers/xml_serializer.rb @@ -23,12 +23,14 @@ module ActiveRecord #:nodoc: # # # This behavior can be controlled with :only, :except, - # :skip_instruct, :skip_types and :dasherize. + # :skip_instruct, :skip_types, :skip_nils and :dasherize. # The :only and :except options are the same as for the # +attributes+ method. The default is to dasherize all column names, but you # can disable this setting :dasherize to +false+. To not have the # column type included in the XML output set :skip_types to +true+. - # + # If you don't want to have the xml element for a nil column present in the + # output, set :skip_nils to +true+. + # # For instance: # # topic.to_xml(:skip_instruct => true, :except => [ :id, :bonus_time, :written_on, :replies_count ]) @@ -215,7 +217,7 @@ module ActiveRecord #:nodoc: dasherize? ? attribute.name.dasherize : attribute.name, attribute.value.to_s, attribute.decorations(!options[:skip_types]) - ) + ) unless options[:skip_nils] && attribute.value.nil? end def add_associations(association, records, opts) diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb index 63f4886..b422393 100644 --- a/activerecord/test/cases/xml_serialization_test.rb +++ b/activerecord/test/cases/xml_serialization_test.rb @@ -115,6 +115,20 @@ class NilXmlSerializationTest < ActiveRecord::TestCase attributes = $1 assert_match %r{type="yaml"}, attributes assert_match %r{nil="true"}, attributes + end +end + +class NilXmlSerializationWithOptionSkipNilTest < ActiveRecord::TestCase + def setup + @xml = Contact.new.to_xml(:skip_nils => true) + end + + def test_should_not_serialize_string + assert !%r{}.match(@xml) + end + + def test_should_not_serialize_integer + assert !%r{}.match(@xml) end end -- 1.6.0.1