Add ArraySerializer#object like Serializer

This commit is contained in:
Benjamin Fleischer 2015-08-24 13:21:49 -05:00
parent 87c47f8fdc
commit dc4ee94fea
3 changed files with 25 additions and 20 deletions

View File

@ -163,19 +163,21 @@ module ActiveModel
def add_links(options)
links = @hash.fetch(:links) { {} }
resources = serializer.instance_variable_get(:@resource)
@hash[:links] = add_pagination_links(links, resources, options) if is_paginated?(resources)
collection = serializer.object
if is_paginated?(collection)
@hash[:links] = add_pagination_links(links, collection, options)
end
end
def add_pagination_links(links, resources, options)
pagination_links = JsonApi::PaginationLinks.new(resources, options[:context]).serializable_hash(options)
def add_pagination_links(links, collection, options)
pagination_links = JsonApi::PaginationLinks.new(collection, options[:context]).serializable_hash(options)
links.update(pagination_links)
end
def is_paginated?(resource)
resource.respond_to?(:current_page) &&
resource.respond_to?(:total_pages) &&
resource.respond_to?(:size)
def is_paginated?(collection)
collection.respond_to?(:current_page) &&
collection.respond_to?(:total_pages) &&
collection.respond_to?(:size)
end
end
end

View File

@ -3,23 +3,22 @@ module ActiveModel
class ArraySerializer
NoSerializerError = Class.new(StandardError)
include Enumerable
delegate :each, to: :@objects
delegate :each, to: :@serializers
attr_reader :root, :meta, :meta_key
attr_reader :object, :root, :meta, :meta_key
def initialize(objects, options = {})
def initialize(resources, options = {})
@root = options[:root]
@resource = objects
@objects = objects.map do |object|
serializer_class = options.fetch(
:serializer,
ActiveModel::Serializer.serializer_for(object)
)
@object = resources
@serializers = resources.map do |resource|
serializer_class = options.fetch(:serializer) {
ActiveModel::Serializer.serializer_for(resource)
}
if serializer_class.nil?
fail NoSerializerError, "No serializer found for object: #{object.inspect}"
fail NoSerializerError, "No serializer found for resource: #{resource.inspect}"
else
serializer_class.new(object, options.except(:serializer))
serializer_class.new(resource, options.except(:serializer))
end
end
@meta = options[:meta]
@ -27,7 +26,7 @@ module ActiveModel
end
def json_key
key = root || @objects.first.try(:json_key) || @resource.try(:name).try(:underscore)
key = root || @serializers.first.try(:json_key) || object.try(:name).try(:underscore)
key.try(:pluralize)
end
end

View File

@ -15,6 +15,10 @@ module ActiveModel
resource
end
def test_has_object_reader_serializer_interface
assert_equal @serializer.object, @resource
end
def test_respond_to_each
assert_respond_to @serializer, :each
end