Permalink
Browse files

Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@te…

…xtdrive.com]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4314 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent aa72c46 commit 3fec943aca9ab73bf00d5dffa3f73452f33bab88 Marcel Molina committed Apr 29, 2006
View
@@ -1,5 +1,7 @@
*SVN*
+* Allow AR::Base#to_xml to include methods too. Closes #4921. [johan@textdrive.com]
+
* Replace superfluous name_to_class_name variant with camelize. [Marcel Molina Jr.]
* Replace alias method chaining with Module#alias_method_chain. [Marcel Molina Jr.]
@@ -1690,13 +1690,29 @@ def readonly! #:nodoc:
# <credit-limit type="integer">50</credit-limit>
# </account>
# </firm>
+ #
+ # To include any methods on the object(s) being called use :methods
+ #
+ # firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
+ #
+ # <firm>
+ # # ... normal attributes as shown above ...
+ # <calculated-earnings>100000000000000000</calculated-earnings>
+ # <real-earnings>5</real-earnings>
+ # </firm>
def to_xml(options = {})
options[:root] ||= self.class.to_s.underscore
options[:except] = Array(options[:except]) << self.class.inheritance_column unless options[:only] # skip type column
root_only_or_except = { :only => options[:only], :except => options[:except] }
attributes_for_xml = attributes(root_only_or_except)
+ if methods_to_call = options.delete(:methods)
+ [*methods_to_call].each do |meth|
+ attributes_for_xml[meth] = send(meth)
+ end
+ end
+
if include_associations = options.delete(:include)
include_has_options = include_associations.is_a?(Hash)
@@ -1273,6 +1273,12 @@ def test_to_xml_including_multiple_associations_with_options
assert xml.include?(%(<clients><client>))
end
+ def test_to_xml_including_methods
+ xml = Company.new.to_xml(:methods => :arbitrary_method, :skip_instruct => true)
+ assert_equal "<company>", xml.first(9)
+ assert xml.include?(%(<arbitrary-method>I am Jack's profound disappointment</arbitrary-method>))
+ end
+
def test_except_attributes
assert_equal(
%w( author_name type id approved replies_count bonus_time written_on content author_email_address parent_id last_read),
@@ -5,6 +5,10 @@ class Company < ActiveRecord::Base
validates_presence_of :name
has_one :dummy_account, :foreign_key => "firm_id", :class_name => "Account"
+
+ def arbitrary_method
+ "I am Jack's profound disappointment"
+ end
end

0 comments on commit 3fec943

Please sign in to comment.