Skip to content

Instantly share code, notes, and snippets.

@dwhenry
Forked from plcstevens/controller_example.rb
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save dwhenry/41b2a2c306b67115769c to your computer and use it in GitHub Desktop.

Select an option

Save dwhenry/41b2a2c306b67115769c 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
include Pagination
def index
@examples = Example.order(id: :desc)
render json: { pagination: paginate(@examples), examples: @examples }
end
end
module Pagination
include ActionDispatch::Routing::UrlFor
def paginate(active_relation)
routes = Routes.new(this, active_relation)
{
records: active_relation.count,
total_records: active_relation.total_count,
current_page: active_relation.current_page,
total_pages: active_relation.total_pages,
first_page: routes.first_page,
last_page: routes.last_page,
prev_page: routes.prev_page,
next_page: routes.next_page,
}
end
class Routes
def initialize(controller, active_relation)
@controller = controller
@active_relation = active_relation
end
def first_page
@controller.url_for(params.merge(page: 1))
end
def last_page
@controller.url_for(params.merge(page: @active_relation.total_pages))
end
def prev_page
@controller.url_for(params.merge(page: @active_relation.prev_page)) unless @active_relation.first_page?
end
def next_page
@controller.url_for(params.merge(page: @active_relation.next_page)) unless @active_relation.last_page?
end
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