mixing :include and :methods in options hash passed to #to_xml

I'm not sure if this would be considered a defect or not, so I wanted to post here before adding a report to Trac. Perhaps someone here is aware of something I'm not.

Let's say I have the following model classes defined:

### BEGIN ### class Foo < ActiveRecord::Base   has_many :bars

  def some_method     "I am some_method"   end end

class Bar < ActiveRecord::Base   belongs_to :foo end ### END ###

If I try to run "Foo.find( 1 ).to_xml( :include => [ :bars ], :methods => [ :some_method ] )" there is a problem, because the options hash passed to Foo#to_xml is passed down to Bar#to_xml when it serializes the associated objects. In general, that's probably what you want -- the problem is that Bar#some_method is not defined, and so you get a NoMethodError when the serialization tries to call #some_method on the Bar instances.

I wonder if it would be a good idea to change the ActiveRecord::XmlSerialization::XmlSerializer#serializable_method_attributes method from

### BEGIN ### def serializable_method_attributes   Array(options[:methods]).collect { |name| MethodAttribute.new(name.to_s, @record) } end ### END ###

to something like

### BEGIN ### def serializable_method_attributes   valid_methods = Array(options[:methods]).reject { |name| !@record.respond_to? name }   valid_methods.collect { |name| MethodAttribute.new(name.to_s, @record) } end ### END ###

Obviously, the danger here is that you do /not/ get an exception if you specify a method in the options that is not defined anywhere in the object graph being serialized. Personally, I think that would be a good trade-off. Otherwise I've found that I have to write a custom #to_xml method in many of my model classes just to remove unknown methods form the :methods option. Better to take care of that once at the root.

Thoughts?

I'm not sure if this would be considered a defect or not, so I wanted to post here before adding a report to Trac. Perhaps someone here is aware of something I'm not.

Let's say I have the following model classes defined:

### BEGIN ### class Foo < ActiveRecord::Base   has_many :bars

  def some_method     "I am some_method"   end end

class Bar < ActiveRecord::Base   belongs_to :foo end ### END ###

If I try to run "Foo.find( 1 ).to_xml( :include => [ :bars ], :methods => [ :some_method ] )" there is a problem, because the options hash passed to Foo#to_xml is passed down to Bar#to_xml when it serializes the associated objects. In general, that's probably what you want -- the problem is that Bar#some_method is not defined, and so you get a NoMethodError when the serialization tries to call #some_method on the Bar instances.

This definitely is a bug, please open a ticket and attach your proposed fix.

While .to_xml isn't designed to be the be-all-and-end-all solution for generating xml, this is well within reason.

Done. http://dev.rubyonrails.org/ticket/7307