Last active
January 3, 2016 13:39
-
-
Save agenticsim/8470962 to your computer and use it in GitHub Desktop.
This file contains 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
class ApplicationController < ActionController::Base | |
#... | |
# this method expects a class to be passed with the attributes @@per_page, | |
# @@:per_page_max defined | |
def prepare_pagination(paginable_class) | |
# STEP 1: Prepare values | |
# STEP 1a: Prepare page | |
# what the client wants or 1 per default | |
page = params[:page].nil?? | |
1 : params[:page].to_i | |
# STEP 1b: Prepare per_page | |
# either use what the client asks for or take the models defaults | |
per_page = params[:per_page].nil?? | |
paginable_class.per_page : params[:per_page].to_i | |
# STEP 2: Sanity checks | |
# STEP 2a: Check page boundaries (page must at leaste be 1, but there are | |
# no max max restrictions, worst case: an empty set will be returned) | |
page = [page, 1].max | |
# STEP 2b: Assure proper boundaries for per_page: | |
# at least one per page but not more than the model allows us | |
per_page = [per_page, 1].max | |
per_page = [per_page, paginable_class.per_page_max].min | |
#return per_page, page | |
return per_page, page | |
end | |
# this method expects a WillPaginate::Collection to be given (aplying | |
# .paginate on models or scopes delivers these objects), examines it and | |
# delivers flincs cutom paginable http headers | |
def set_pagination_headers(p) | |
return unless p.is_a?(WillPaginate::Collection) | |
response.headers["X-Pagination-Total-Entries"] = p.total_entries.to_s | |
response.headers["X-Pagination-Per-Page"] = p.per_page.to_s | |
response.headers["X-Pagination-Total-Pages"] = p.total_pages.to_s | |
response.headers["X-Pagination-Current-Page"] = p.current_page.to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment