Skip to content

Instantly share code, notes, and snippets.

@sqrtsanta
Last active August 29, 2015 14:25
Show Gist options
  • Save sqrtsanta/5dc2ce4a15661b8a0f6c to your computer and use it in GitHub Desktop.
Save sqrtsanta/5dc2ce4a15661b8a0f6c to your computer and use it in GitHub Desktop.
Reverse pagination
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
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