Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

When serialising a class, specify the type of any singular associations,... #7858

Closed
wants to merge 1 commit into
from
Jump to file or symbol
Failed to load files and symbols.
+13 −3
Split
@@ -140,7 +140,9 @@ def add_associations(association, records, opts)
end
else
merged_options[:root] = association.to_s
- records.to_xml(merged_options)
+ association_name = association.to_s.tableize.singularize
@rafaelfranca

rafaelfranca Oct 6, 2012

Owner

This need a refactoring.

association_name = association.to_s
record_class = record.class

merged_options[:root] = association_name

if record_class.to_s.underscore == association_name.tableize.singularize
  merged_options[:type] = record_class.name
end

records.to_xml(merged_options)
+ record_type = { :type => ((records.class.to_s.underscore == association_name) ? nil : records.class.name) }
+ records.to_xml merged_options.merge(record_type)
end
end
@@ -7,12 +7,12 @@ class Contact
extend ActiveModel::Naming
include ActiveModel::Serializers::Xml
- attr_accessor :address, :friends
+ attr_accessor :address, :friends, :contact
remove_method :attributes if method_defined?(:attributes)
def attributes
- instance_values.except("address", "friends")
+ instance_values.except("address", "friends", "contact")
end
end
@@ -57,6 +57,9 @@ def setup
@contact.address.state = "CA"
@contact.address.zip = 11111
@contact.friends = [Contact.new, Contact.new]
+ @related_contact = SerializableContact.new
+ @related_contact.name = "related"
+ @contact.contact = @related_contact
end
test "should serialize default root" do
@@ -205,4 +208,9 @@ def setup
assert_match %r{<friends>}, xml
assert_match %r{<friend>}, xml
end
+
+ test "association with sti" do
+ xml = @contact.to_xml(:include => :contact)
+ assert xml.include?(%(<contact type="SerializableContact">))
+ end
end