Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #6258 (closed defect: untested)

Opened 2 years ago

Last modified 2 years ago

[PATCH] Pass record to options hash in to_xml

Reported by: canadaduane Assigned to: David
Priority: normal Milestone: 1.x
Component: ActiveRecord Version: edge
Severity: normal Keywords: to_xml serialization xml procs
Cc:

Description

When to_xml is called with an :include, and if there is also one or more :procs passed in, the procs will be evaluated for the "current record" as well as all "included records" without any provision for differentiating which record the proc is acting on.

For example:

  include_content_id = proc do |options| xml = options[:builder]
    xml.tag! 'content_id', content_id 
  end
  user.to_xml(:include => [:addresses], :procs => [include_content_id])

In this case, (supposing the value of user.content_id = 1), both the "user" xml *AND* the each of the "addresses" xml will contain a

  <content-id>1</content-id>

The same problem occurs when :methods => [:content_id] is used (except that there will be an exception raised in my case, because Address objects do not have a content_id method).

As a work-around for the case of procs, I suggest adding a :record key to the options hash that is passed in to the proc. This record would then contain information about the "current record" and could be used to distinguish which of the included ActiveRecord objects are being XML serialized.

  include_content_id = proc do |options| xml = options[:builder]
    if options[:record].respond_to? :content_id
      xml.tag! 'content_id', options[:record].content_id 
    end
  end

The code necessary to permit this is a very simple change to the XmlSerializer initialize method.

Attachments

to_xml_passes_record_to_proc.diff (507 bytes) - added by canadaduane on 09/21/06 18:16:00.

Change History

09/21/06 18:16:00 changed by canadaduane

  • attachment to_xml_passes_record_to_proc.diff added.

09/21/06 23:47:59 changed by bitsweat

  • status changed from new to closed.
  • resolution set to untested.