Let's say I have the following model classes defined:
class Foo < ActiveRecord::Base
has_many :bars
def some_method
"I am some_method"
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
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
def serializable_method_attributes
Array(options[:methods]).collect { |name| MethodAttribute.new(name.to_s, @record) }
end
to something like
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
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 from
the :methods option. Better to take care of that once at the root.