Skip to content

Instantly share code, notes, and snippets.

@plcstevens
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save plcstevens/7c4ebab540e52f8655d8 to your computer and use it in GitHub Desktop.
Save plcstevens/7c4ebab540e52f8655d8 to your computer and use it in GitHub Desktop.
Include this in controllers and render with your JSON to get pagination URLs matching http://jsonapi.org/format/#fetching-pagination specification. Requires that you use https://github.com/amatsuda/kaminari
class ExamplesController < ApplicationController
def index
@examples = Example.order(id: :desc)
render json: { pagination: paginate(@examples), examples: @examples }
end
private
def paginate(active_relation)
Pagination.for(self, active_relation)
end
end
class Pagination
def self.for(controller, active_relation)
new(controller, active_relation).paginate
end
attr_reader :controller, :active_relation
delegate :params, :url_for, to: :controller
delegate :count, :total_count, :current_page, :total_pages,
:prev_page, :next_page, :first_page?, :last_page?, to: :active_relation
def initialize(controller, active_relation)
@controller = controller
@active_relation = active_relation
end
def first_page_url
url_for(params.merge(page: 1))
end
def last_page_url
url_for(params.merge(page: total_pages))
end
def prev_page_url
url_for(params.merge(page: prev_page)) unless first_page?
end
def next_page_url
url_for(params.merge(page: next_page)) unless last_page?
end
def paginate
{
records: count,
total_records: total_count,
current_page: current_page,
total_pages: total_pages,
first_page: first_page_url,
last_page: last_page_url,
prev_page: prev_page_url,
next_page: next_page_url,
}
end
end
{
"pagination": {
"records": 5,
"total_records": 21,
"current_page": 1,
"total_pages": 5,
"first_page": "http://example.com/examples?page=1&per_page=5",
"last_page": "http://example.com/examples?page=5&per_page=5",
"prev_page": null,
"next_page": "http://example.com/examples?page=2&per_page=5"
},
"examples": [
{
"id": 1
},
{
"id": 2
},
{
"id": 3
},
{
"id": 4
},
{
"id": 5
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment