Skip to content

Commit

Permalink
Add :only/:except options
Browse files Browse the repository at this point in the history
  • Loading branch information
wojtekmach authored and Adrian Mugnolo committed Mar 12, 2014
1 parent 3201c63 commit 2e31a14
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/active_model/serializer.rb
Expand Up @@ -108,6 +108,8 @@ def initialize(object, options={})
@meta_key = options[:meta_key] || :meta
@meta = options[@meta_key]
@wrap_in_array = options[:_wrap_in_array]
@only = Array(options[:only]) if options[:only]
@except = Array(options[:except]) if options[:except]

This comment has been minimized.

Copy link
@tonywok

tonywok May 12, 2014

Are these options passed to associations serializers?

For example, if I want to ?include=comments, is there any way I can tell comments to include something? (contrived example)

end
attr_accessor :object, :scope, :root, :meta_key, :meta

Expand Down Expand Up @@ -140,7 +142,13 @@ def associations
end

def filter(keys)
keys

This comment has been minimized.

Copy link
@tchak

tchak May 4, 2014

Contributor

this means that when overriding filter method we need to always call super. Given how this is a common pattern seems like a bad idea. And if you really want to keep it this way, we need to change documentation in the README... Would you be ok with a private wrapper around filter method to make filter easily overridable again? I am happy to provide a PR in this case.

if @only
keys & @only
elsif @except
keys - @except
else
keys
end
end

def embedded_in_root_associations
Expand Down
20 changes: 20 additions & 0 deletions test/unit/active_model/serializer/filter_test.rb
Expand Up @@ -2,6 +2,26 @@

module ActiveModel
class Serializer
class FilterOptionsTest < Minitest::Test
def setup
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })
end

def test_only_option
@profile_serializer = ProfileSerializer.new(@profile, only: :name)
assert_equal({
'profile' => { name: 'Name 1' }
}, @profile_serializer.as_json)
end

def test_except_option
@profile_serializer = ProfileSerializer.new(@profile, except: :comments)
assert_equal({
'profile' => { name: 'Name 1', description: 'Description 1' }
}, @profile_serializer.as_json)
end
end

class FilterAttributesTest < Minitest::Test
def setup
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })
Expand Down

0 comments on commit 2e31a14

Please sign in to comment.