From c39151a84768397d3bb025c6e8f877eac59ebbf9 Mon Sep 17 00:00:00 2001 From: John Maxwell Date: Wed, 22 Jul 2009 20:47:15 -0500 Subject: Patch to ActiveModel's (and ActiveRecord, by association) XML serialization: If two parameters are present in Procs supplied to to_xml's :procs option, the model being serialized will be passed as the second argument [#2373 state:resolved] Signed-off-by: Joshua Peek --- .../lib/active_record/serializers/xml_serializer.rb | 15 +++++++++++++++ activerecord/test/cases/xml_serialization_test.rb | 6 ++++++ 2 files changed, 21 insertions(+) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/serializers/xml_serializer.rb b/activerecord/lib/active_record/serializers/xml_serializer.rb index 253fa03785..4e172bd2b6 100644 --- a/activerecord/lib/active_record/serializers/xml_serializer.rb +++ b/activerecord/lib/active_record/serializers/xml_serializer.rb @@ -71,6 +71,21 @@ module ActiveRecord #:nodoc: # # # + # Additionally, the record being serialized will be passed to a Proc's second + # parameter. This allows for ad hoc additions to the resultant document that + # incorporate the context of the record being serialized. And by leveraging the + # closure created by a Proc, to_xml can be used to add elements that normally fall + # outside of the scope of the model -- for example, generating and appending URLs + # associated with models. + # + # proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) } + # firm.to_xml :procs => [ proc ] + # + # + # # ... normal attributes as shown above ... + # slangis73 + # + # # To include deeper levels of associations pass a hash like this: # # firm.to_xml :include => {:account => {}, :clients => {:include => :address}} diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb index b49997669e..e1ad5c1685 100644 --- a/activerecord/test/cases/xml_serialization_test.rb +++ b/activerecord/test/cases/xml_serialization_test.rb @@ -174,6 +174,12 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase assert_match %r{Danish}, xml end + def test_dual_arity_procs_are_called_on_object + proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) } + xml = authors(:david).to_xml(:procs => [ proc ]) + assert_match %r{divaD}, xml + end + def test_top_level_procs_arent_applied_to_associations author_proc = Proc.new { |options| options[:builder].tag!('nationality', 'Danish') } xml = authors(:david).to_xml(:procs => [ author_proc ], :include => :posts, :indent => 2) -- cgit v1.2.3