Last active
August 29, 2015 14:14
-
-
Save artworx/7979a634794fa7fd8c6c to your computer and use it in GitHub Desktop.
rails pagination headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ApiPagination | |
protected | |
def api_paginate(collection, options = {}) | |
links = (headers['Link'] || "").split(',').map(&:strip) | |
url = request.original_url.sub(/\?.*$/, '') | |
pages = pages_from(collection) | |
pages.each do |k, v| | |
new_params = request.query_parameters.merge(:page => v) | |
links << %(<#{url}?#{new_params.to_param}>; rel="#{k}") | |
end | |
headers['Link'] = links.join(', ') unless links.empty? | |
headers['Total'] = [collection.total_entries] | |
headers['X-Pagination-Total-Results'] = [collection.total_entries] | |
end | |
def pages_from(collection) | |
{}.tap do |pages| | |
if collection.previous_page | |
pages[:prev] = collection.current_page - 1 | |
end | |
if collection.next_page | |
pages[:next] = collection.current_page + 1 | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment