Skip to content

Commit

Permalink
Merge pull request #1 from metermd/master
Browse files Browse the repository at this point in the history
Allow for the implicit use of ArraySerializer when :each_serializer is specified
  • Loading branch information
ggordon committed Nov 7, 2014
2 parents c84430c + 58b6c4a commit 3925f93
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 6 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,12 @@ If you wish to use a serializer other than the default, you can explicitly pass
#### 2. For an array resource:

```ruby
render json: @posts, serializer: PaginatedSerializer, each_serializer: PostPreviewSerializer
# Use the default `ArraySerializer`, which will use `each_serializer` to
# serialize each element
render json: @posts, each_serializer: PostPreviewSerializer

# Or, you can explicitly provide the collection serializer as well
render json: @posts, serializer: PaginatedSerializer, each_serializer: PostPreviewSerializer
```

## Installation
Expand Down
12 changes: 7 additions & 5 deletions lib/action_controller/serialization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ module Serialization
ADAPTER_OPTION_KEYS = [:include, :root]

def get_serializer(resource, options)
@_serializer ||= if (serializer = options.delete :serializer)
options[:serializer] = options.delete :each_serializer
serializer
else
ActiveModel::Serializer.serializer_for(resource)
@_serializer ||= options.delete(:serializer)
@_serializer ||= ActiveModel::Serializer.serializer_for(resource)

if options.key?(:each_serializer)
options[:serializer] = options.delete(:each_serializer)
end

@_serializer
end

[:_render_option_json, :_render_with_renderer_json].each do |renderer_method|
Expand Down
25 changes: 25 additions & 0 deletions test/action_controller/explicit_serializer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@ def render_array_using_explicit_serializer
serializer: PaginatedSerializer,
each_serializer: ProfilePreviewSerializer
end

def render_array_using_implicit_serializer
array = [
Profile.new(name: 'Name 1',
description: 'Description 1',
comments: 'Comments 1'),
Profile.new(name: 'Name 2',
description: 'Description 2',
comments: 'Comments 2')
]
render json: array,
each_serializer: ProfilePreviewSerializer
end
end

tests MyController
Expand All @@ -48,6 +61,18 @@ def test_render_array_using_explicit_serializer

assert_equal expected.to_json, @response.body
end

def test_render_array_using_explicit_serializer
get :render_array_using_implicit_serializer
assert_equal 'application/json', @response.content_type

expected = [
{ 'name' => 'Name 1' },
{ 'name' => 'Name 2' }
]
assert_equal expected.to_json, @response.body
end

end
end
end

0 comments on commit 3925f93

Please sign in to comment.