active_model_serializers/lib/active_model/serializer/collection_serializer.rb
Ben Woosley 251e33a0a1 Don't pluralize the CollectionSerializer#root for #json_key
One of three constituents is used to provide the
CollectionSerializer's #json_key:

1) the :root option - controlled by the caller
2) the #name of the first resource serializer - the root or
   underscored model name
3) the underscored #name of the resources object - generally
   equivalent to the underscored model name of #2

Of the three, only the latter 2 are out of the callers control, and
only the latter two are expected to be singular by default. Not
pluralizing the root gives the caller additional flexibility in
defining the desired root, whether conventionally plural,
unconventionally plural (e.g. objects_received:) or singular.
2016-01-12 09:32:43 -08:00

48 lines
1.3 KiB
Ruby

module ActiveModel
class Serializer
class CollectionSerializer
NoSerializerError = Class.new(StandardError)
include Enumerable
delegate :each, to: :@serializers
attr_reader :object, :root
def initialize(resources, options = {})
@root = options[:root]
@object = resources
@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?
fail NoSerializerError, "No serializer found for resource: #{resource.inspect}"
else
serializer_class.new(resource, options.except(:serializer))
end
end
end
def json_key
root || derived_root
end
def paginated?
object.respond_to?(:current_page) &&
object.respond_to?(:total_pages) &&
object.respond_to?(:size)
end
protected
attr_reader :serializers
private
def derived_root
key = serializers.first.try(:json_key) || object.try(:name).try(:underscore)
key.try(:pluralize)
end
end
end
end