mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
simplified the API for include_associations!() to make conditional includes cleaner
This commit is contained in:
@@ -37,10 +37,11 @@ class SerializerTest < ActiveModel::TestCase
|
||||
def initialize(attributes)
|
||||
super(attributes)
|
||||
self.comments ||= []
|
||||
self.comments_disabled = false
|
||||
self.author = nil
|
||||
end
|
||||
|
||||
attr_accessor :comments, :author
|
||||
attr_accessor :comments, :comments_disabled, :author
|
||||
def active_model_serializer; PostSerializer; end
|
||||
end
|
||||
|
||||
@@ -89,11 +90,6 @@ class SerializerTest < ActiveModel::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
attributes :title, :body
|
||||
has_many :comments, :serializer => CommentSerializer
|
||||
end
|
||||
|
||||
def test_scope_works_correct
|
||||
serializer = ActiveModel::Serializer.new :foo, :scope => :bar
|
||||
assert_equal serializer.scope, :bar
|
||||
@@ -163,6 +159,11 @@ class SerializerTest < ActiveModel::TestCase
|
||||
}, hash)
|
||||
end
|
||||
|
||||
class PostSerializer < ActiveModel::Serializer
|
||||
attributes :title, :body
|
||||
has_many :comments, :serializer => CommentSerializer
|
||||
end
|
||||
|
||||
def test_has_many
|
||||
user = User.new
|
||||
|
||||
@@ -184,6 +185,48 @@ class SerializerTest < ActiveModel::TestCase
|
||||
}, post_serializer.as_json)
|
||||
end
|
||||
|
||||
class PostWithConditionalCommentsSerializer < ActiveModel::Serializer
|
||||
root :post
|
||||
attributes :title, :body
|
||||
has_many :comments, :serializer => CommentSerializer
|
||||
|
||||
def include_associations!
|
||||
include! :comments unless object.comments_disabled
|
||||
end
|
||||
end
|
||||
|
||||
def test_conditionally_included_associations
|
||||
user = User.new
|
||||
|
||||
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
|
||||
|
||||
post_serializer = PostWithConditionalCommentsSerializer.new(post, :scope => user)
|
||||
|
||||
# comments enabled
|
||||
post.comments_disabled = false
|
||||
assert_equal({
|
||||
:post => {
|
||||
:title => "New Post",
|
||||
:body => "Body of new post",
|
||||
:comments => [
|
||||
{ :title => "Comment1" },
|
||||
{ :title => "Comment2" }
|
||||
]
|
||||
}
|
||||
}, post_serializer.as_json)
|
||||
|
||||
# comments disabled
|
||||
post.comments_disabled = true
|
||||
assert_equal({
|
||||
:post => {
|
||||
:title => "New Post",
|
||||
:body => "Body of new post"
|
||||
}
|
||||
}, post_serializer.as_json)
|
||||
end
|
||||
|
||||
class Blog < Model
|
||||
attr_accessor :author
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user