]> git.openstreetmap.org Git - rails.git/blob - lib/classic_pagination/pagination.rb
Use 'def setup' instead of 'setup do', for consistency
[rails.git] / lib / classic_pagination / pagination.rb
1 module ActionController
2   # === Action Pack pagination for Active Record collections
3   #
4   # The Pagination module aids in the process of paging large collections of
5   # Active Record objects. It offers macro-style automatic fetching of your
6   # model for multiple views, or explicit fetching for single actions. And if
7   # the magic isn't flexible enough for your needs, you can create your own
8   # paginators with a minimal amount of code.
9   #
10   # The Pagination module can handle as much or as little as you wish. In the
11   # controller, have it automatically query your model for pagination; or,
12   # if you prefer, create Paginator objects yourself.
13   #
14   # Pagination is included automatically for all controllers.
15   #
16   # For help rendering pagination links, see
17   # ActionView::Helpers::PaginationHelper.
18   #
19   # ==== Automatic pagination for every action in a controller
20   #
21   #   class PersonController < ApplicationController
22   #     model :person
23   #
24   #     paginate :people, :order => 'last_name, first_name',
25   #              :per_page => 20
26   #
27   #     # ...
28   #   end
29   #
30   # Each action in this controller now has access to a <tt>@people</tt>
31   # instance variable, which is an ordered collection of model objects for the
32   # current page (at most 20, sorted by last name and first name), and a
33   # <tt>@person_pages</tt> Paginator instance. The current page is determined
34   # by the <tt>params[:page]</tt> variable.
35   #
36   # ==== Pagination for a single action
37   #
38   #   def list
39   #     @person_pages, @people =
40   #       paginate :people, :order => 'last_name, first_name'
41   #   end
42   #
43   # Like the previous example, but explicitly creates <tt>@person_pages</tt>
44   # and <tt>@people</tt> for a single action, and uses the default of 10 items
45   # per page.
46   #
47   # ==== Custom/"classic" pagination
48   #
49   #   def list
50   #     @person_pages = Paginator.new self, Person.count, 10, params[:page]
51   #     @people = Person.find :all, :order => 'last_name, first_name',
52   #                           :limit  =>  @person_pages.items_per_page,
53   #                           :offset =>  @person_pages.current.offset
54   #   end
55   #
56   # Explicitly creates the paginator from the previous example and uses
57   # Paginator#to_sql to retrieve <tt>@people</tt> from the model.
58   #
59   module Pagination
60     if const_defined?(:OPTIONS)
61       DEFAULT_OPTIONS[:group] = nil
62     else
63       # A hash holding options for controllers using macro-style pagination
64       OPTIONS = {}.freeze
65
66       # The default options for pagination
67       DEFAULT_OPTIONS = {
68         :class_name => nil,
69         :singular_name => nil,
70         :per_page   => 10,
71         :conditions => nil,
72         :order_by   => nil,
73         :order      => nil,
74         :join       => nil,
75         :joins      => nil,
76         :count      => nil,
77         :include    => nil,
78         :select     => nil,
79         :group      => nil,
80         :parameter  => "page"
81       }.freeze
82     end
83
84     def self.included(base) #:nodoc:
85       super
86       base.extend(ClassMethods)
87     end
88
89     def self.validate_options!(collection_id, options, in_action) #:nodoc:
90       options.merge!(DEFAULT_OPTIONS) { |_key, old, _new| old }
91
92       valid_options = DEFAULT_OPTIONS.keys
93       valid_options << :actions unless in_action
94
95       unknown_option_keys = options.keys - valid_options
96       raise ActionController::ActionControllerError,
97             "Unknown options: #{unknown_option_keys.join(', ')}" unless
98               unknown_option_keys.empty?
99
100       options[:singular_name] ||= ActiveSupport::Inflector.singularize(collection_id.to_s)
101       options[:class_name] ||= ActiveSupport::Inflector.camelize(options[:singular_name])
102     end
103
104     # Returns a paginator and a collection of Active Record model instances
105     # for the paginator's current page. This is designed to be used in a
106     # single action; to automatically paginate multiple actions, consider
107     # ClassMethods#paginate.
108     #
109     # +options+ are:
110     # <tt>:singular_name</tt>:: the singular name to use, if it can't be inferred by singularizing the collection name
111     # <tt>:class_name</tt>:: the class name to use, if it can't be inferred by
112     #                        camelizing the singular name
113     # <tt>:per_page</tt>::   the maximum number of items to include in a
114     #                        single page. Defaults to 10
115     # <tt>:conditions</tt>:: optional conditions passed to Model.find(:all, *params) and
116     #                        Model.count
117     # <tt>:order</tt>::      optional order parameter passed to Model.find(:all, *params)
118     # <tt>:order_by</tt>::   (deprecated, used :order) optional order parameter passed to Model.find(:all, *params)
119     # <tt>:joins</tt>::      optional joins parameter passed to Model.find(:all, *params)
120     #                        and Model.count
121     # <tt>:join</tt>::       (deprecated, used :joins or :include) optional join parameter passed to Model.find(:all, *params)
122     #                        and Model.count
123     # <tt>:include</tt>::    optional eager loading parameter passed to Model.find(:all, *params)
124     #                        and Model.count
125     # <tt>:select</tt>::     :select parameter passed to Model.find(:all, *params)
126     #
127     # <tt>:count</tt>::      parameter passed as :select option to Model.count(*params)
128     #
129     # <tt>:group</tt>::     :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
130     #
131     def paginate(collection_id, options = {})
132       Pagination.validate_options!(collection_id, options, true)
133       paginator_and_collection_for(collection_id, options)
134     end
135
136     # These methods become class methods on any controller
137     module ClassMethods
138       # Creates a +before_filter+ which automatically paginates an Active
139       # Record model for all actions in a controller (or certain actions if
140       # specified with the <tt>:actions</tt> option).
141       #
142       # +options+ are the same as PaginationHelper#paginate, with the addition
143       # of:
144       # <tt>:actions</tt>:: an array of actions for which the pagination is
145       #                     active. Defaults to +nil+ (i.e., every action)
146       def paginate(collection_id, options = {})
147         Pagination.validate_options!(collection_id, options, false)
148         module_eval do
149           before_filter :create_paginators_and_retrieve_collections
150           OPTIONS[self] ||= {}
151           OPTIONS[self][collection_id] = options
152         end
153       end
154     end
155
156     def create_paginators_and_retrieve_collections #:nodoc:
157       Pagination::OPTIONS[self.class].each do |collection_id, options|
158         next if options[:actions] && !options[:actions].include?(action_name)
159
160         paginator, collection =
161           paginator_and_collection_for(collection_id, options)
162
163         paginator_name = "@#{options[:singular_name]}_pages"
164         instance_variable_set(paginator_name, paginator)
165
166         collection_name = "@#{collection_id}"
167         instance_variable_set(collection_name, collection)
168       end
169     end
170
171     # Returns the total number of items in the collection to be paginated for
172     # the +model+ and given +conditions+. Override this method to implement a
173     # custom counter.
174     def count_collection_for_pagination(model, options)
175       collection = model.joins(options[:join] || options[:joins])
176       collection = collection.where(options[:conditions])
177       collection = collection.includes(options[:include])
178
179       if options[:group]
180         collection = collection.select(options[:group]).distinct
181       elsif options[:count]
182         collection = collection.select(options[:count])
183       end
184
185       collection.count
186     end
187
188     # Returns a collection of items for the given +model+ and +options[conditions]+,
189     # ordered by +options[order]+, for the current page in the given +paginator+.
190     # Override this method to implement a custom finder.
191     def find_collection_for_pagination(model, options, paginator)
192       collection = model.joins(options[:join] || options[:joins])
193       collection = collection.where(options[:conditions])
194       collection = collection.order(options[:order_by] || options[:order])
195       collection = collection.includes(options[:include])
196       collection = collection.group(options[:group])
197       collection = collection.select(options[:select]) if options[:select]
198
199       collection.offset(paginator.current.offset).limit(options[:per_page])
200     end
201
202     protected :create_paginators_and_retrieve_collections,
203               :count_collection_for_pagination,
204               :find_collection_for_pagination
205
206     def paginator_and_collection_for(_collection_id, options) #:nodoc:
207       klass = options[:class_name].constantize
208       page  = params[options[:parameter]]
209       count = count_collection_for_pagination(klass, options)
210       paginator = Paginator.new(self, count, options[:per_page], page)
211       collection = find_collection_for_pagination(klass, options, paginator)
212
213       [paginator, collection]
214     end
215
216     private :paginator_and_collection_for
217
218     # A class representing a paginator for an Active Record collection.
219     class Paginator
220       include Enumerable
221
222       # Creates a new Paginator on the given +controller+ for a set of items
223       # of size +item_count+ and having +items_per_page+ items per page.
224       # Raises ArgumentError if items_per_page is out of bounds (i.e., less
225       # than or equal to zero). The page CGI parameter for links defaults to
226       # "page" and can be overridden with +page_parameter+.
227       def initialize(controller, item_count, items_per_page, current_page = 1)
228         raise ArgumentError, "must have at least one item per page" if
229           items_per_page <= 0
230
231         @controller = controller
232         @item_count = item_count || 0
233         @items_per_page = items_per_page
234         @pages = {}
235
236         self.current_page = current_page
237       end
238       attr_reader :controller, :item_count, :items_per_page
239
240       # Sets the current page number of this paginator. If +page+ is a Page
241       # object, its +number+ attribute is used as the value; if the page does
242       # not belong to this Paginator, an ArgumentError is raised.
243       def current_page=(page)
244         if page.is_a? Page
245           raise ArgumentError, "Page/Paginator mismatch" unless
246             page.paginator == self
247         end
248         page = page.to_i
249         @current_page_number = has_page_number?(page) ? page : 1
250       end
251
252       # Returns a Page object representing this paginator's current page.
253       def current_page
254         @current_page ||= self[@current_page_number]
255       end
256       alias current current_page
257
258       # Returns a new Page representing the first page in this paginator.
259       def first_page
260         @first_page ||= self[1]
261       end
262       alias first first_page
263
264       # Returns a new Page representing the last page in this paginator.
265       def last_page
266         @last_page ||= self[page_count]
267       end
268       alias last last_page
269
270       # Returns the number of pages in this paginator.
271       def page_count
272         @page_count ||= if @item_count.zero?
273                           1
274                         else
275                           q, r = @item_count.divmod(@items_per_page)
276                           r.zero? ? q : q + 1
277                         end
278       end
279
280       alias length page_count
281
282       # Returns true if this paginator contains the page of index +number+.
283       def has_page_number?(number)
284         number >= 1 && number <= page_count
285       end
286
287       # Returns a new Page representing the page with the given index
288       # +number+.
289       def [](number)
290         @pages[number] ||= Page.new(self, number)
291       end
292
293       # Successively yields all the paginator's pages to the given block.
294       def each(&_block)
295         page_count.times do |n|
296           yield self[n + 1]
297         end
298       end
299
300       # A class representing a single page in a paginator.
301       class Page
302         include Comparable
303
304         # Creates a new Page for the given +paginator+ with the index
305         # +number+. If +number+ is not in the range of valid page numbers or
306         # is not a number at all, it defaults to 1.
307         def initialize(paginator, number)
308           @paginator = paginator
309           @number = number.to_i
310           @number = 1 unless @paginator.has_page_number? @number
311         end
312         attr_reader :paginator, :number
313         alias to_i number
314
315         # Compares two Page objects and returns true when they represent the
316         # same page (i.e., their paginators are the same and they have the
317         # same page number).
318         def ==(other)
319           return false if other.nil?
320           @paginator == other.paginator &&
321             @number == other.number
322         end
323
324         # Compares two Page objects and returns -1 if the left-hand page comes
325         # before the right-hand page, 0 if the pages are equal, and 1 if the
326         # left-hand page comes after the right-hand page. Raises ArgumentError
327         # if the pages do not belong to the same Paginator object.
328         def <=>(other)
329           raise ArgumentError unless @paginator == other.paginator
330           @number <=> other.number
331         end
332
333         # Returns the item offset for the first item in this page.
334         def offset
335           @paginator.items_per_page * (@number - 1)
336         end
337
338         # Returns the number of the first item displayed.
339         def first_item
340           offset + 1
341         end
342
343         # Returns the number of the last item displayed.
344         def last_item
345           [@paginator.items_per_page * @number, @paginator.item_count].min
346         end
347
348         # Returns true if this page is the first page in the paginator.
349         def first?
350           self == @paginator.first
351         end
352
353         # Returns true if this page is the last page in the paginator.
354         def last?
355           self == @paginator.last
356         end
357
358         # Returns a new Page object representing the page just before this
359         # page, or nil if this is the first page.
360         def previous
361           first? ? nil : @paginator[@number - 1]
362         end
363
364         # Returns a new Page object representing the page just after this
365         # page, or nil if this is the last page.
366         def next
367           last? ? nil : @paginator[@number + 1]
368         end
369
370         # Returns a new Window object for this page with the specified
371         # +padding+.
372         def window(padding = 2)
373           Window.new(self, padding)
374         end
375
376         # Returns the limit/offset array for this page.
377         def to_sql
378           [@paginator.items_per_page, offset]
379         end
380
381         def to_param #:nodoc:
382           @number.to_s
383         end
384       end
385
386       # A class for representing ranges around a given page.
387       class Window
388         # Creates a new Window object for the given +page+ with the specified
389         # +padding+.
390         def initialize(page, padding = 2)
391           @paginator = page.paginator
392           @page = page
393           self.padding = padding
394         end
395         attr_reader :paginator, :page
396
397         # Sets the window's padding (the number of pages on either side of the
398         # window page).
399         def padding=(padding)
400           @padding = padding < 0 ? 0 : padding
401           # Find the beginning and end pages of the window
402           @first = if @paginator.has_page_number?(@page.number - @padding)
403                      @paginator[@page.number - @padding]
404                    else
405                      @paginator.first
406                    end
407           @last = if @paginator.has_page_number?(@page.number + @padding)
408                     @paginator[@page.number + @padding]
409                   else
410                     @paginator.last
411                   end
412         end
413         attr_reader :padding, :first, :last
414
415         # Returns an array of Page objects in the current window.
416         def pages
417           (@first.number..@last.number).to_a.collect! { |n| @paginator[n] }
418         end
419         alias to_a pages
420       end
421     end
422   end
423 end