Merge pull request #1041 from bacarini/master

Adding pagination links
This commit is contained in:
João Moura
2015-08-22 13:38:32 -03:00
13 changed files with 614 additions and 181 deletions

View File

@@ -1,4 +1,5 @@
require 'active_model/serializer/adapter/json_api/fragment_cache'
require 'active_model/serializer/adapter/json_api/pagination_links'
module ActiveModel
class Serializer
@@ -27,6 +28,8 @@ module ActiveModel
@hash[:included] |= result[:included]
end
end
add_links(options)
else
@hash[:data] = attributes_for_serializer(serializer, options)
add_resource_relationships(@hash[:data], serializer)
@@ -157,6 +160,23 @@ module ActiveModel
end
end
end
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)
end
def add_pagination_links(links, resources, options)
pagination_links = JsonApi::PaginationLinks.new(resources, 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)
end
end
end
end

View File

@@ -0,0 +1,58 @@
module ActiveModel
class Serializer
class Adapter
class JsonApi < Adapter
class PaginationLinks
FIRST_PAGE = 1
attr_reader :collection, :context
def initialize(collection, context)
@collection = collection
@context = context
end
def serializable_hash(options = {})
pages_from.each_with_object({}) do |(key, value), hash|
params = query_parameters.merge(page: { number: value, size: collection.size }).to_query
hash[key] = "#{url(options)}?#{params}"
end
end
private
def pages_from
return {} if collection.total_pages == FIRST_PAGE
{}.tap do |pages|
pages[:self] = collection.current_page
unless collection.current_page == FIRST_PAGE
pages[:first] = FIRST_PAGE
pages[:prev] = collection.current_page - FIRST_PAGE
end
unless collection.current_page == collection.total_pages
pages[:next] = collection.current_page + FIRST_PAGE
pages[:last] = collection.total_pages
end
end
end
def url(options)
@url ||= options.fetch(:links, {}).fetch(:self, nil) || original_url
end
def original_url
@original_url ||= context.original_url[/\A[^?]+/]
end
def query_parameters
@query_parameters ||= context.query_parameters
end
end
end
end
end
end