Add association_ids

This commit is contained in:
Jose and Yehuda 2011-10-15 18:27:56 +02:00
parent 22c322f056
commit 322f47898e
2 changed files with 89 additions and 2 deletions

@ -18,12 +18,25 @@ def serialize(collection, scope)
serializer.new(item, scope).serializable_hash
end
end
def serialize_ids(collection, scope)
# use named scopes if they are present
return collection.ids if collection.respond_to?(:ids)
collection.map do |item|
item.read_attribute_for_serialization(:id)
end
end
end
class HasOne < Config
def serialize(object, scope)
serializer.new(object, scope).serializable_hash
end
def serialize_ids(object, scope)
object.read_attribute_for_serialization(:id)
end
end
end
@ -80,7 +93,11 @@ def as_json(*)
end
def serializable_hash
hash = attributes
attributes.merge(associations)
end
def associations
hash = {}
_associations.each do |association|
associated_object = send(association.name)
@ -90,6 +107,17 @@ def serializable_hash
hash
end
def association_ids
hash = {}
_associations.each do |association|
associated_object = send(association.name)
hash[association.name] = association.serialize_ids(associated_object, scope)
end
hash
end
def attributes
hash = {}

@ -182,11 +182,12 @@ def test_overridden_associations
blog_serializer = Class.new(ActiveModel::Serializer) do
const_set(:PersonSerializer, author_serializer)
has_one :person
def person
object.author
end
has_one :person
end
user = User.new
@ -200,4 +201,62 @@ def person
}
}, json)
end
def post_serializer(type)
Class.new(ActiveModel::Serializer) do
attributes :title, :body
has_many :comments, :serializer => CommentSerializer
define_method :serializable_hash do
post_hash = attributes
post_hash.merge!(send(type))
post_hash
end
end
end
def test_associations
post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com")
comments = [Comment.new(:title => "Comment1"), Comment.new(:title => "Comment2")]
post.comments = comments
serializer = post_serializer(:associations).new(post, nil)
assert_equal({
:title => "New Post",
:body => "Body of new post",
:comments => [
{ :title => "Comment1" },
{ :title => "Comment2" }
]
}, serializer.as_json)
end
def test_association_ids
serializer = post_serializer(:association_ids)
serializer.class_eval do
def as_json(*)
{ post: serializable_hash }.merge(associations)
end
end
post = Post.new(:title => "New Post", :body => "Body of new post", :email => "tenderlove@tenderlove.com")
comments = [Comment.new(:title => "Comment1", :id => 1), Comment.new(:title => "Comment2", :id => 2)]
post.comments = comments
serializer = serializer.new(post, nil)
assert_equal({
:post => {
:title => "New Post",
:body => "Body of new post",
:comments => [1, 2]
},
:comments => [
{ :title => "Comment1" },
{ :title => "Comment2" }
]
}, serializer.as_json)
end
end