Chris@909: module ActionController Chris@909: # === Action Pack pagination for Active Record collections Chris@909: # Chris@909: # The Pagination module aids in the process of paging large collections of Chris@909: # Active Record objects. It offers macro-style automatic fetching of your Chris@909: # model for multiple views, or explicit fetching for single actions. And if Chris@909: # the magic isn't flexible enough for your needs, you can create your own Chris@909: # paginators with a minimal amount of code. Chris@909: # Chris@909: # The Pagination module can handle as much or as little as you wish. In the Chris@909: # controller, have it automatically query your model for pagination; or, Chris@909: # if you prefer, create Paginator objects yourself. Chris@909: # Chris@909: # Pagination is included automatically for all controllers. Chris@909: # Chris@909: # For help rendering pagination links, see Chris@909: # ActionView::Helpers::PaginationHelper. Chris@909: # Chris@909: # ==== Automatic pagination for every action in a controller Chris@909: # Chris@909: # class PersonController < ApplicationController Chris@909: # model :person Chris@909: # Chris@909: # paginate :people, :order => 'last_name, first_name', Chris@909: # :per_page => 20 Chris@909: # Chris@909: # # ... Chris@909: # end Chris@909: # Chris@909: # Each action in this controller now has access to a @people Chris@909: # instance variable, which is an ordered collection of model objects for the Chris@909: # current page (at most 20, sorted by last name and first name), and a Chris@909: # @person_pages Paginator instance. The current page is determined Chris@909: # by the params[:page] variable. Chris@909: # Chris@909: # ==== Pagination for a single action Chris@909: # Chris@909: # def list Chris@909: # @person_pages, @people = Chris@909: # paginate :people, :order => 'last_name, first_name' Chris@909: # end Chris@909: # Chris@909: # Like the previous example, but explicitly creates @person_pages Chris@909: # and @people for a single action, and uses the default of 10 items Chris@909: # per page. Chris@909: # Chris@909: # ==== Custom/"classic" pagination Chris@909: # Chris@909: # def list Chris@909: # @person_pages = Paginator.new self, Person.count, 10, params[:page] Chris@909: # @people = Person.find :all, :order => 'last_name, first_name', Chris@909: # :limit => @person_pages.items_per_page, Chris@909: # :offset => @person_pages.current.offset Chris@909: # end Chris@909: # Chris@909: # Explicitly creates the paginator from the previous example and uses Chris@909: # Paginator#to_sql to retrieve @people from the model. Chris@909: # Chris@909: module Pagination Chris@909: unless const_defined?(:OPTIONS) Chris@909: # A hash holding options for controllers using macro-style pagination Chris@909: OPTIONS = Hash.new Chris@909: Chris@909: # The default options for pagination Chris@909: DEFAULT_OPTIONS = { Chris@909: :class_name => nil, Chris@909: :singular_name => nil, Chris@909: :per_page => 10, Chris@909: :conditions => nil, Chris@909: :order_by => nil, Chris@909: :order => nil, Chris@909: :join => nil, Chris@909: :joins => nil, Chris@909: :count => nil, Chris@909: :include => nil, Chris@909: :select => nil, Chris@909: :group => nil, Chris@909: :parameter => 'page' Chris@909: } Chris@909: else Chris@909: DEFAULT_OPTIONS[:group] = nil Chris@909: end Chris@909: Chris@909: def self.included(base) #:nodoc: Chris@909: super Chris@909: base.extend(ClassMethods) Chris@909: end Chris@909: Chris@909: def self.validate_options!(collection_id, options, in_action) #:nodoc: Chris@909: options.merge!(DEFAULT_OPTIONS) {|key, old, new| old} Chris@909: Chris@909: valid_options = DEFAULT_OPTIONS.keys Chris@909: valid_options << :actions unless in_action Chris@909: Chris@909: unknown_option_keys = options.keys - valid_options Chris@909: raise ActionController::ActionControllerError, Chris@909: "Unknown options: #{unknown_option_keys.join(', ')}" unless Chris@909: unknown_option_keys.empty? Chris@909: Chris@909: options[:singular_name] ||= ActiveSupport::Inflector.singularize(collection_id.to_s) Chris@909: options[:class_name] ||= ActiveSupport::Inflector.camelize(options[:singular_name]) Chris@909: end Chris@909: Chris@909: # Returns a paginator and a collection of Active Record model instances Chris@909: # for the paginator's current page. This is designed to be used in a Chris@909: # single action; to automatically paginate multiple actions, consider Chris@909: # ClassMethods#paginate. Chris@909: # Chris@909: # +options+ are: Chris@909: # :singular_name:: the singular name to use, if it can't be inferred by singularizing the collection name Chris@909: # :class_name:: the class name to use, if it can't be inferred by Chris@909: # camelizing the singular name Chris@909: # :per_page:: the maximum number of items to include in a Chris@909: # single page. Defaults to 10 Chris@909: # :conditions:: optional conditions passed to Model.find(:all, *params) and Chris@909: # Model.count Chris@909: # :order:: optional order parameter passed to Model.find(:all, *params) Chris@909: # :order_by:: (deprecated, used :order) optional order parameter passed to Model.find(:all, *params) Chris@909: # :joins:: optional joins parameter passed to Model.find(:all, *params) Chris@909: # and Model.count Chris@909: # :join:: (deprecated, used :joins or :include) optional join parameter passed to Model.find(:all, *params) Chris@909: # and Model.count Chris@909: # :include:: optional eager loading parameter passed to Model.find(:all, *params) Chris@909: # and Model.count Chris@909: # :select:: :select parameter passed to Model.find(:all, *params) Chris@909: # Chris@909: # :count:: parameter passed as :select option to Model.count(*params) Chris@909: # Chris@909: # :group:: :group parameter passed to Model.find(:all, *params). It forces the use of DISTINCT instead of plain COUNT to come up with the total number of records Chris@909: # Chris@909: def paginate(collection_id, options={}) Chris@909: Pagination.validate_options!(collection_id, options, true) Chris@909: paginator_and_collection_for(collection_id, options) Chris@909: end Chris@909: Chris@909: # These methods become class methods on any controller Chris@909: module ClassMethods Chris@909: # Creates a +before_filter+ which automatically paginates an Active Chris@909: # Record model for all actions in a controller (or certain actions if Chris@909: # specified with the :actions option). Chris@909: # Chris@909: # +options+ are the same as PaginationHelper#paginate, with the addition Chris@909: # of: Chris@909: # :actions:: an array of actions for which the pagination is Chris@909: # active. Defaults to +nil+ (i.e., every action) Chris@909: def paginate(collection_id, options={}) Chris@909: Pagination.validate_options!(collection_id, options, false) Chris@909: module_eval do Chris@909: before_filter :create_paginators_and_retrieve_collections Chris@909: OPTIONS[self] ||= Hash.new Chris@909: OPTIONS[self][collection_id] = options Chris@909: end Chris@909: end Chris@909: end Chris@909: Chris@909: def create_paginators_and_retrieve_collections #:nodoc: Chris@909: Pagination::OPTIONS[self.class].each do |collection_id, options| Chris@909: next unless options[:actions].include? action_name if Chris@909: options[:actions] Chris@909: Chris@909: paginator, collection = Chris@909: paginator_and_collection_for(collection_id, options) Chris@909: Chris@909: paginator_name = "@#{options[:singular_name]}_pages" Chris@909: self.instance_variable_set(paginator_name, paginator) Chris@909: Chris@909: collection_name = "@#{collection_id.to_s}" Chris@909: self.instance_variable_set(collection_name, collection) Chris@909: end Chris@909: end Chris@909: Chris@909: # Returns the total number of items in the collection to be paginated for Chris@909: # the +model+ and given +conditions+. Override this method to implement a Chris@909: # custom counter. Chris@909: def count_collection_for_pagination(model, options) Chris@909: model.count(:conditions => options[:conditions], Chris@909: :joins => options[:join] || options[:joins], Chris@909: :include => options[:include], Chris@909: :select => (options[:group] ? "DISTINCT #{options[:group]}" : options[:count])) Chris@909: end Chris@909: Chris@909: # Returns a collection of items for the given +model+ and +options[conditions]+, Chris@909: # ordered by +options[order]+, for the current page in the given +paginator+. Chris@909: # Override this method to implement a custom finder. Chris@909: def find_collection_for_pagination(model, options, paginator) Chris@909: model.find(:all, :conditions => options[:conditions], Chris@909: :order => options[:order_by] || options[:order], Chris@909: :joins => options[:join] || options[:joins], :include => options[:include], Chris@909: :select => options[:select], :limit => options[:per_page], Chris@909: :group => options[:group], :offset => paginator.current.offset) Chris@909: end Chris@909: Chris@909: protected :create_paginators_and_retrieve_collections, Chris@909: :count_collection_for_pagination, Chris@909: :find_collection_for_pagination Chris@909: Chris@909: def paginator_and_collection_for(collection_id, options) #:nodoc: Chris@909: klass = options[:class_name].constantize Chris@909: page = params[options[:parameter]] Chris@909: count = count_collection_for_pagination(klass, options) Chris@909: paginator = Paginator.new(self, count, options[:per_page], page) Chris@909: collection = find_collection_for_pagination(klass, options, paginator) Chris@909: Chris@909: return paginator, collection Chris@909: end Chris@909: Chris@909: private :paginator_and_collection_for Chris@909: Chris@909: # A class representing a paginator for an Active Record collection. Chris@909: class Paginator Chris@909: include Enumerable Chris@909: Chris@909: # Creates a new Paginator on the given +controller+ for a set of items Chris@909: # of size +item_count+ and having +items_per_page+ items per page. Chris@909: # Raises ArgumentError if items_per_page is out of bounds (i.e., less Chris@909: # than or equal to zero). The page CGI parameter for links defaults to Chris@909: # "page" and can be overridden with +page_parameter+. Chris@909: def initialize(controller, item_count, items_per_page, current_page=1) Chris@909: raise ArgumentError, 'must have at least one item per page' if Chris@909: items_per_page <= 0 Chris@909: Chris@909: @controller = controller Chris@909: @item_count = item_count || 0 Chris@909: @items_per_page = items_per_page Chris@909: @pages = {} Chris@909: Chris@909: self.current_page = current_page Chris@909: end Chris@909: attr_reader :controller, :item_count, :items_per_page Chris@909: Chris@909: # Sets the current page number of this paginator. If +page+ is a Page Chris@909: # object, its +number+ attribute is used as the value; if the page does Chris@909: # not belong to this Paginator, an ArgumentError is raised. Chris@909: def current_page=(page) Chris@909: if page.is_a? Page Chris@909: raise ArgumentError, 'Page/Paginator mismatch' unless Chris@909: page.paginator == self Chris@909: end Chris@909: page = page.to_i Chris@909: @current_page_number = has_page_number?(page) ? page : 1 Chris@909: end Chris@909: Chris@909: # Returns a Page object representing this paginator's current page. Chris@909: def current_page Chris@909: @current_page ||= self[@current_page_number] Chris@909: end Chris@909: alias current :current_page Chris@909: Chris@909: # Returns a new Page representing the first page in this paginator. Chris@909: def first_page Chris@909: @first_page ||= self[1] Chris@909: end Chris@909: alias first :first_page Chris@909: Chris@909: # Returns a new Page representing the last page in this paginator. Chris@909: def last_page Chris@909: @last_page ||= self[page_count] Chris@909: end Chris@909: alias last :last_page Chris@909: Chris@909: # Returns the number of pages in this paginator. Chris@909: def page_count Chris@909: @page_count ||= @item_count.zero? ? 1 : Chris@909: (q,r=@item_count.divmod(@items_per_page); r==0? q : q+1) Chris@909: end Chris@909: Chris@909: alias length :page_count Chris@909: Chris@909: # Returns true if this paginator contains the page of index +number+. Chris@909: def has_page_number?(number) Chris@909: number >= 1 and number <= page_count Chris@909: end Chris@909: Chris@909: # Returns a new Page representing the page with the given index Chris@909: # +number+. Chris@909: def [](number) Chris@909: @pages[number] ||= Page.new(self, number) Chris@909: end Chris@909: Chris@909: # Successively yields all the paginator's pages to the given block. Chris@909: def each(&block) Chris@909: page_count.times do |n| Chris@909: yield self[n+1] Chris@909: end Chris@909: end Chris@909: Chris@909: # A class representing a single page in a paginator. Chris@909: class Page Chris@909: include Comparable Chris@909: Chris@909: # Creates a new Page for the given +paginator+ with the index Chris@909: # +number+. If +number+ is not in the range of valid page numbers or Chris@909: # is not a number at all, it defaults to 1. Chris@909: def initialize(paginator, number) Chris@909: @paginator = paginator Chris@909: @number = number.to_i Chris@909: @number = 1 unless @paginator.has_page_number? @number Chris@909: end Chris@909: attr_reader :paginator, :number Chris@909: alias to_i :number Chris@909: Chris@909: # Compares two Page objects and returns true when they represent the Chris@909: # same page (i.e., their paginators are the same and they have the Chris@909: # same page number). Chris@909: def ==(page) Chris@909: return false if page.nil? Chris@909: @paginator == page.paginator and Chris@909: @number == page.number Chris@909: end Chris@909: Chris@909: # Compares two Page objects and returns -1 if the left-hand page comes Chris@909: # before the right-hand page, 0 if the pages are equal, and 1 if the Chris@909: # left-hand page comes after the right-hand page. Raises ArgumentError Chris@909: # if the pages do not belong to the same Paginator object. Chris@909: def <=>(page) Chris@909: raise ArgumentError unless @paginator == page.paginator Chris@909: @number <=> page.number Chris@909: end Chris@909: Chris@909: # Returns the item offset for the first item in this page. Chris@909: def offset Chris@909: @paginator.items_per_page * (@number - 1) Chris@909: end Chris@909: Chris@909: # Returns the number of the first item displayed. Chris@909: def first_item Chris@909: offset + 1 Chris@909: end Chris@909: Chris@909: # Returns the number of the last item displayed. Chris@909: def last_item Chris@909: [@paginator.items_per_page * @number, @paginator.item_count].min Chris@909: end Chris@909: Chris@909: # Returns true if this page is the first page in the paginator. Chris@909: def first? Chris@909: self == @paginator.first Chris@909: end Chris@909: Chris@909: # Returns true if this page is the last page in the paginator. Chris@909: def last? Chris@909: self == @paginator.last Chris@909: end Chris@909: Chris@909: # Returns a new Page object representing the page just before this Chris@909: # page, or nil if this is the first page. Chris@909: def previous Chris@909: if first? then nil else @paginator[@number - 1] end Chris@909: end Chris@909: Chris@909: # Returns a new Page object representing the page just after this Chris@909: # page, or nil if this is the last page. Chris@909: def next Chris@909: if last? then nil else @paginator[@number + 1] end Chris@909: end Chris@909: Chris@909: # Returns a new Window object for this page with the specified Chris@909: # +padding+. Chris@909: def window(padding=2) Chris@909: Window.new(self, padding) Chris@909: end Chris@909: Chris@909: # Returns the limit/offset array for this page. Chris@909: def to_sql Chris@909: [@paginator.items_per_page, offset] Chris@909: end Chris@909: Chris@909: def to_param #:nodoc: Chris@909: @number.to_s Chris@909: end Chris@909: end Chris@909: Chris@909: # A class for representing ranges around a given page. Chris@909: class Window Chris@909: # Creates a new Window object for the given +page+ with the specified Chris@909: # +padding+. Chris@909: def initialize(page, padding=2) Chris@909: @paginator = page.paginator Chris@909: @page = page Chris@909: self.padding = padding Chris@909: end Chris@909: attr_reader :paginator, :page Chris@909: Chris@909: # Sets the window's padding (the number of pages on either side of the Chris@909: # window page). Chris@909: def padding=(padding) Chris@909: @padding = padding < 0 ? 0 : padding Chris@909: # Find the beginning and end pages of the window Chris@909: @first = @paginator.has_page_number?(@page.number - @padding) ? Chris@909: @paginator[@page.number - @padding] : @paginator.first Chris@909: @last = @paginator.has_page_number?(@page.number + @padding) ? Chris@909: @paginator[@page.number + @padding] : @paginator.last Chris@909: end Chris@909: attr_reader :padding, :first, :last Chris@909: Chris@909: # Returns an array of Page objects in the current window. Chris@909: def pages Chris@909: (@first.number..@last.number).to_a.collect! {|n| @paginator[n]} Chris@909: end Chris@909: alias to_a :pages Chris@909: end Chris@909: end Chris@909: Chris@909: end Chris@909: end