[FIX] Fetch json key from item serializer if empty collection is passed to collection serializer and each_searializer is specified.

This commit is contained in:
Roman Kapitonov 2016-02-24 21:03:36 +03:00 committed by Benjamin Fleischer
parent 33a0f9c806
commit 2dd0c33461
3 changed files with 29 additions and 4 deletions

View File

@ -10,8 +10,14 @@ module ActiveModel
def initialize(resources, options = {})
@root = options[:root]
@object = resources
serializer_context_class = options.fetch(:serializer_context_class, ActiveModel::Serializer)
if resources.blank? && options[:serializer]
@each_serializer = options[:serializer]
end
@serializers = resources.map do |resource|
serializer_context_class = options.fetch(:serializer_context_class, ActiveModel::Serializer)
serializer_class = options.fetch(:serializer) { serializer_context_class.serializer_for(resource) }
if serializer_class.nil? # rubocop:disable Style/GuardClause
@ -27,7 +33,7 @@ module ActiveModel
end
def json_key
root || derived_root
root || derived_root || guess_root || default_root
end
def paginated?
@ -43,8 +49,15 @@ module ActiveModel
private
def derived_root
key = serializers.first.try(:json_key) || object.try(:name).try(:underscore)
key.try(:pluralize)
serializers.first.try(:json_key).try(:pluralize)
end
def default_root
object.try(:name).try(:underscore).try(:pluralize)
end
def guess_root
@each_serializer.try(:allocate).try(:json_key).try(:pluralize)
end
end
end

View File

@ -84,6 +84,12 @@ module ActiveModel
assert_nil serializer.json_key
end
def test_json_key_with_empty_resources_with_serializer
resource = []
serializer = collection_serializer.new(resource, serializer: MessagesSerializer)
assert_equal 'messages', serializer.json_key
end
def test_json_key_with_root
expected = 'custom_root'
serializer = collection_serializer.new(@resource, root: expected)

View File

@ -183,6 +183,12 @@ PaginatedSerializer = Class.new(ActiveModel::Serializer::CollectionSerializer) d
end
end
MessagesSerializer = Class.new(ActiveModel::Serializer) do
def json_key
'messages'
end
end
AlternateBlogSerializer = Class.new(ActiveModel::Serializer) do
attribute :id
attribute :name, key: :title