Skip to content

Instantly share code, notes, and snippets.

@artworx
Last active August 29, 2015 14:14
Show Gist options
  • Save artworx/7979a634794fa7fd8c6c to your computer and use it in GitHub Desktop.
Save artworx/7979a634794fa7fd8c6c to your computer and use it in GitHub Desktop.
rails pagination headers
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