Last active
January 26, 2016 08:47
-
-
Save ryantownsend/8eb32c306ec680a2100a to your computer and use it in GitHub Desktop.
Provides consistent JSON-API compliant pagination methods
This file contains hidden or 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
| # | |
| # Api::Paginatable | |
| # | |
| # Provides consistent JSON-API compliant pagination methods | |
| # | |
| module Api::Paginatable | |
| extend ActiveSupport::Concern | |
| protected | |
| # receives a ActiveRecord::Relation, applies pagination and returns | |
| # implement in your index action as `self.resource = apply_pagination(resource)` | |
| def apply_pagination(scope, size: pagination_page_size, number: pagination_page_number) | |
| scope = scope.per([size, pagination_page_size_limit].min) if size | |
| scope = scope.page(number) if number | |
| scope | |
| end | |
| private | |
| # returns the current page number as specified by page[number] | |
| def pagination_page_number | |
| if params[:page] && params[:page][:number] | |
| Integer(params[:page][:number]) | |
| end | |
| end | |
| # returns the requested size of page as specified by page[size] | |
| def pagination_page_size | |
| if params[:page] && params[:page][:size] | |
| Integer(params[:page][:size]) | |
| end | |
| end | |
| # defines a hard limit on page size to prevent people asking for millions of rows | |
| # override in specific controllers to allow for larger pages where sensible | |
| def pagination_page_size_limit | |
| 500 | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment