Skip to content

Commit a848372

Browse files
committed
Merge pull request #665 from andreychernih/fix-each-serializer-option
Make sure `render json: ..., each_serializer: ...` is working with Enumerables
2 parents 40d53aa + 90343ce commit a848372

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

lib/action_controller/serialization.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def build_json_serializer(resource, options = {})
8484
if serializer = options.fetch(:serializer, default_serializer(resource))
8585
options[:scope] = serialization_scope unless options.has_key?(:scope)
8686

87-
if resource.respond_to?(:to_ary)
87+
if resource.respond_to?(:each)
8888
options[:resource_name] = controller_name
8989
options[:namespace] = namespace_for_serializer if namespace_for_serializer
9090
end

lib/active_model/serializer.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def format_keys(format)
5656
attr_reader :key_format
5757

5858
def serializer_for(resource, options = {})
59-
if resource.respond_to?(:to_ary)
59+
if resource.respond_to?(:each)
6060
if Object.constants.include?(:ArraySerializer)
6161
::ArraySerializer
6262
else

test/fixtures/poro.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,10 @@ def description
9292
attributes :name, :description
9393
end
9494

95+
class DifferentProfileSerializer < ActiveModel::Serializer
96+
attributes :name
97+
end
98+
9599
class CategorySerializer < ActiveModel::Serializer
96100
attributes :name
97101

test/integration/action_controller/serialization_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,5 +283,21 @@ def test_render_array_embeding_in_root
283283
assert_equal("{\"my\":[{\"name\":\"Name 1\",\"email\":\"[email protected]\",\"profile_id\":#{@controller.user.profile.object_id}}],\"profiles\":[{\"name\":\"N1\",\"description\":\"D1\"}]}", @response.body)
284284
end
285285
end
286+
287+
class ExplicitEachSerializerWithEnumarableObjectTest < ActionController::TestCase
288+
class MyController < ActionController::Base
289+
def render_array
290+
render json: [Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })].to_enum, each_serializer: DifferentProfileSerializer
291+
end
292+
end
293+
294+
tests MyController
295+
296+
def test_render_array
297+
get :render_array
298+
assert_equal 'application/json', @response.content_type
299+
assert_equal '{"my":[{"name":"Name 1"}]}', @response.body
300+
end
301+
end
286302
end
287303
end

0 commit comments

Comments
 (0)