Skip to content

Instantly share code, notes, and snippets.

@agenticsim
Last active January 3, 2016 13:39

Revisions

  1. sunseesiu revised this gist Jan 17, 2014. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion pagination.rb
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    class ApplicationController < ActionController::Base
    class ApplicationController < ActionController::Base
    #...
    # this method expects a class to be passed with the attributes @@per_page,
    # @@:per_page_max defined
  2. sunseesiu created this gist Jan 17, 2014.
    41 changes: 41 additions & 0 deletions pagination.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    class ApplicationController &lt; 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