Last active
August 29, 2015 14:25
-
-
Save sqrtsanta/5dc2ce4a15661b8a0f6c to your computer and use it in GitHub Desktop.
Reverse pagination
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
class ReversePagination | |
attr_reader :page, :per_page, :total_count, :total_pages, :records | |
def initialize(scope, page) | |
initialize_params(scope.klass, page) | |
@records = scope.limit(limit).offset(offset).order(:created_at).reverse | |
end | |
def initialize_params(klass, page) | |
@per_page = klass::PER_PAGE | |
@total_count = klass.count | |
@total_pages = total_count / per_page | |
@page = page.to_i | |
@page = total_pages if @page <= 0 || @page > total_pages | |
end | |
def limit | |
per_page + 1 / (total_pages - page + 1) * (total_count % per_page) | |
end | |
def offset | |
(page - 1) * per_page | |
end | |
end |
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
class UsersController < ApplicationController | |
def index | |
@users = reverse_paginate User.includes(:likes), params[:page] | |
end | |
private | |
def reverse_paginate(scope, page) | |
@paginator = ReversePagination.new(scope, page) | |
@paginator.records | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment