mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 15:23:06 +00:00
exchange pagination class to inside json_api scope
This commit is contained in:
@@ -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
|
||||
|
||||
include_pagination_links if serializer.pagination
|
||||
else
|
||||
@hash[:data] = attributes_for_serializer(serializer, options)
|
||||
add_resource_relationships(@hash[:data], serializer)
|
||||
@@ -157,6 +160,20 @@ module ActiveModel
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def include_pagination_links
|
||||
return if page_links.empty?
|
||||
|
||||
links? ? @hash[:links].merge!(page_links) : @hash[:links] = page_links
|
||||
end
|
||||
|
||||
def page_links
|
||||
@links ||= JsonApi::PaginationLinks.new(serializer.resource).page_links
|
||||
end
|
||||
|
||||
def links?
|
||||
!@hash[:links].nil?
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
class Adapter
|
||||
class JsonApi < Adapter
|
||||
class PaginationLinks
|
||||
FIRST_PAGE = 1
|
||||
|
||||
attr_reader :collection
|
||||
|
||||
def initialize(collection)
|
||||
raise_unless_any_gem_installed
|
||||
@collection = collection
|
||||
end
|
||||
|
||||
def page_links
|
||||
build_links
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def build_links
|
||||
pages_from.each_with_object({}) do |(key, value), hash|
|
||||
hash[key] = "?page=#{value}&per_page=#{collection.size}"
|
||||
end
|
||||
end
|
||||
|
||||
def pages_from
|
||||
return {} if collection.total_pages == FIRST_PAGE
|
||||
|
||||
{}.tap do |pages|
|
||||
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 raise_unless_any_gem_installed
|
||||
return if defined?(WillPaginate) || defined?(Kaminari)
|
||||
raise "AMS relies on either Kaminari or WillPaginate." +
|
||||
"Please install either dependency by adding one of those to your Gemfile"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user