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