mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
[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:
parent
33a0f9c806
commit
2dd0c33461
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
6
test/fixtures/poro.rb
vendored
6
test/fixtures/poro.rb
vendored
@ -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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user