mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 14:56:50 +00:00
Basic rooted polymorphism
This commit is contained in:
parent
56824f055b
commit
32f8779114
@ -216,13 +216,26 @@ module ActiveModel
|
|||||||
end
|
end
|
||||||
|
|
||||||
class HasOne < Config #:nodoc:
|
class HasOne < Config #:nodoc:
|
||||||
|
def polymorphic?
|
||||||
|
option :polymorphic
|
||||||
|
end
|
||||||
|
|
||||||
|
def polymoprhic_key
|
||||||
|
associated_object.class.to_s.demodulize.underscore.to_sym
|
||||||
|
end
|
||||||
|
|
||||||
def plural_key
|
def plural_key
|
||||||
key.to_s.pluralize.to_sym
|
key.to_s.pluralize.to_sym
|
||||||
end
|
end
|
||||||
|
|
||||||
def serialize
|
def serialize
|
||||||
object = associated_object
|
object = associated_object
|
||||||
object && find_serializable(object).serializable_hash
|
|
||||||
|
if object && polymorphic?
|
||||||
|
{ polymoprhic_key => find_serializable(object).serializable_hash }
|
||||||
|
elsif object
|
||||||
|
find_serializable(object).serializable_hash
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def serialize_many
|
def serialize_many
|
||||||
|
|||||||
@ -957,4 +957,46 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
:foo => true
|
:foo => true
|
||||||
}, actual)
|
}, actual)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Set up some classes for polymorphic testing
|
||||||
|
class Attachment < Model
|
||||||
|
def attachable
|
||||||
|
@attributes[:attachable]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def tests_can_handle_polymorphism
|
||||||
|
email_serializer = Class.new(ActiveModel::Serializer) do
|
||||||
|
attributes :subject, :body
|
||||||
|
end
|
||||||
|
|
||||||
|
email_class = Class.new(Model) do
|
||||||
|
def self.to_s
|
||||||
|
"Email"
|
||||||
|
end
|
||||||
|
|
||||||
|
define_method :active_model_serializer do
|
||||||
|
email_serializer
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
attachment_serializer = Class.new(ActiveModel::Serializer) do
|
||||||
|
attributes :name, :url
|
||||||
|
has_one :attachable, :polymorphic => true
|
||||||
|
end
|
||||||
|
|
||||||
|
email = email_class.new :subject => 'foo', :body => 'bar'
|
||||||
|
|
||||||
|
attachment = Attachment.new :name => 'logo.png', :url => 'http://example.com/logo.png', :attachable => email
|
||||||
|
|
||||||
|
actual = attachment_serializer.new(attachment, {}).as_json
|
||||||
|
|
||||||
|
assert_equal({
|
||||||
|
:name => 'logo.png',
|
||||||
|
:url => 'http://example.com/logo.png',
|
||||||
|
:attachable => {
|
||||||
|
:email => { :subject => 'foo', :body => 'bar' }
|
||||||
|
}
|
||||||
|
}, actual)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user