mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 23:06:50 +00:00
Added support for :only and :except methods.
It is possible now to filter returned attributes and associations by: UserSerializer.new(user, only: [:first_name, :last_name]) UserSerializer.new(user, except: :first_name)
This commit is contained in:
parent
329a38a7dd
commit
489ebf2132
@ -363,6 +363,8 @@ module ActiveModel
|
|||||||
end
|
end
|
||||||
|
|
||||||
def include?(name)
|
def include?(name)
|
||||||
|
return false if options.key?(:only) && !Array(options[:only]).include?(name)
|
||||||
|
return false if options.key?(:except) && Array(options[:except]).include?(name)
|
||||||
send INCLUDE_METHODS[name]
|
send INCLUDE_METHODS[name]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|||||||
@ -1390,4 +1390,53 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
a_serializer = serializer.new(post, :scope => user, :scope_name => :current_user)
|
a_serializer = serializer.new(post, :scope => user, :scope_name => :current_user)
|
||||||
assert a_serializer.has_permission?
|
assert a_serializer.has_permission?
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_only_option_filters_attributes_and_associations
|
||||||
|
post = Post.new(:title => "New Post", :body => "Body of new post")
|
||||||
|
comments = [Comment.new(:title => "Comment1")]
|
||||||
|
post.comments = comments
|
||||||
|
|
||||||
|
post_serializer = PostSerializer.new(post, :only => :title)
|
||||||
|
|
||||||
|
assert_equal({
|
||||||
|
:post => {
|
||||||
|
:title => "New Post"
|
||||||
|
}
|
||||||
|
}, post_serializer.as_json)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_except_option_filters_attributes_and_associations
|
||||||
|
post = Post.new(:title => "New Post", :body => "Body of new post")
|
||||||
|
comments = [Comment.new(:title => "Comment1")]
|
||||||
|
post.comments = comments
|
||||||
|
|
||||||
|
post_serializer = PostSerializer.new(post, :except => [:body, :comments])
|
||||||
|
|
||||||
|
assert_equal({
|
||||||
|
:post => {
|
||||||
|
:title => "New Post"
|
||||||
|
}
|
||||||
|
}, post_serializer.as_json)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_only_option_takes_precedence_over_custom_defined_include_methods
|
||||||
|
user = User.new
|
||||||
|
|
||||||
|
post = Post.new(:title => "New Post", :body => "Body of new post", :author => "Sausage King")
|
||||||
|
comments = [Comment.new(:title => "Comment")]
|
||||||
|
post.comments = comments
|
||||||
|
|
||||||
|
post_serializer = PostWithMultipleConditionalsSerializer.new(post, :scope => user, :only => :title)
|
||||||
|
|
||||||
|
# comments enabled
|
||||||
|
post.comments_disabled = false
|
||||||
|
# superuser - should see author
|
||||||
|
user.superuser = true
|
||||||
|
|
||||||
|
assert_equal({
|
||||||
|
:post => {
|
||||||
|
:title => "New Post"
|
||||||
|
}
|
||||||
|
}, post_serializer.as_json)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user