Created
March 8, 2011 18:50
-
-
Save gmgent/860760 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
module Extensions | |
module ActiveRecord | |
# Understands how to generate counts and entries for the given scope, and offers some reasonable | |
# pagination helper methods. | |
class Paginator | |
attr_reader :count, :entries, :page, :per_page | |
def initialize(scope, opts={}) | |
@page = opts[:page].try(:to_i) || first_page | |
@per_page = opts[:per_page].try(:to_i) || scope.proxy_scope.per_page | |
@count = scope.count | |
@entries = scope.paginate(:page => @page, :per_page => @per_page).all | |
end | |
def total_pages | |
(count / per_page) + 1 | |
end | |
alias :last_page :total_pages | |
def has_next_page? | |
page < total_pages | |
end | |
def has_prev_page? | |
page > first_page | |
end | |
def first_page; 1; end | |
end | |
module Paginate | |
def per_page | |
@per_page || 10 | |
end | |
def per_page=(per_page) | |
@per_page = per_page | |
end | |
# Applies a pagination scope using the :page and :per_page options passed in. If none given, | |
# defaults to page 1 and this model's per_page setting. Can be used independently of paginator. | |
def paginate(opts={}) | |
page = opts[:page].try(:to_i) || 1 | |
per_page = opts[:per_page].try(:to_i) || per_page | |
scoped :limit => per_page, ffset => (page - 1) * per_page | |
end | |
# Returns an instance of Extensions::ActiveRecord::Paginator applied to the current scope. Used | |
# as the last call in a scope/association chain. There is no need to apply the +paginate+ scope if | |
# you use this method. | |
def paginator(opts={}) | |
Extensions::ActiveRecord::Paginator.new(self.scoped({}), opts.slice(:page, :per_page)) | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send :extend, Extensions::ActiveRecord::Paginate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment