paginator class

17 June 2010 | 9:58 am by codeboxer

lives in extensions/active_record

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, :offset => (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

Recommend Me




My Site Links

Screenshots are featured above. If you visit gmgpulse, you may login as demo/demo.

Rockstar Television


© 2008-10 Krister Axel and codeboxer.com