module FetcheableOnApi::Pageable
Pageable
implements pagination support.
It handles the controller parameters:
-
page[:number]
the requested page (default: 1). -
page[:size]
number of records per page.
If no page
parameter is present on the request, the full collection is returned.
The following pagination information is add to the response headers:
-
Pagination-Current-Page
the page that is returned. -
Pagination-Per
the number of records included in the page. -
Pagination-Total-Pages
the total number of pages available. -
Pagination-Total-Count
the total number of records available.
Protected Instance Methods
apply_pagination(collection)
click to toggle source
Protected instance methods
# File lib/fetcheable_on_api/pageable.rb, line 39 def apply_pagination(collection) return collection if params[:page].blank? foa_valid_parameters!(:page) limit, offset, count, page = extract_pagination_informations(collection) define_header_pagination(limit, count, page) collection.limit(limit).offset(offset) end
Private Instance Methods
define_header_pagination(limit, count, page)
click to toggle source
# File lib/fetcheable_on_api/pageable.rb, line 52 def define_header_pagination(limit, count, page) response.headers["Pagination-Current-Page"] = page response.headers["Pagination-Per"] = limit response.headers["Pagination-Total-Pages"] = (count.to_f / limit.to_f).ceil response.headers["Pagination-Total-Count"] = count end
extract_pagination_informations(collection)
click to toggle source
# File lib/fetcheable_on_api/pageable.rb, line 59 def extract_pagination_informations(collection) limit = params[:page].fetch( :size, FetcheableOnApi.configuration.pagination_default_size ).to_i page = params[:page].fetch(:number, 1).to_i offset = (page - 1) * limit count = collection.except(:offset, :limit, :order).count [limit, offset, count, page] end