You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pagination.rb 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. unless const_defined?(:OPTIONS)
  61. # A hash holding options for controllers using macro-style pagination
  62. OPTIONS = Hash.new
  63. # The default options for pagination
  64. DEFAULT_OPTIONS = {
  65. :class_name => nil,
  66. :singular_name => nil,
  67. :per_page => 10,
  68. :conditions => nil,
  69. :order_by => nil,
  70. :order => nil,
  71. :join => nil,
  72. :joins => nil,
  73. :count => nil,
  74. :include => nil,
  75. :select => nil,
  76. :group => nil,
  77. :parameter => 'page'
  78. }
  79. else
  80. DEFAULT_OPTIONS[:group] = nil
  81. end
  82. def self.included(base) #:nodoc:
  83. super
  84. base.extend(ClassMethods)
  85. end
  86. def self.validate_options!(collection_id, options, in_action) #:nodoc:
  87. options.merge!(DEFAULT_OPTIONS) {|key, old, new| old}
  88. valid_options = DEFAULT_OPTIONS.keys
  89. valid_options << :actions unless in_action
  90. unknown_option_keys = options.keys - valid_options
  91. raise ActionController::ActionControllerError,
  92. "Unknown options: #{unknown_option_keys.join(', ')}" unless
  93. unknown_option_keys.empty?
  94. options[:singular_name] ||= Inflector.singularize(collection_id.to_s)
  95. options[:class_name] ||= Inflector.camelize(options[:singular_name])
  96. end
  97. # Returns a paginator and a collection of Active Record model instances
  98. # for the paginator's current page. This is designed to be used in a
  99. # single action; to automatically paginate multiple actions, consider
  100. # ClassMethods#paginate.
  101. #
  102. # +options+ are:
  103. # <tt>:singular_name</tt>:: the singular name to use, if it can't be inferred by singularizing the collection name
  104. # <tt>:class_name</tt>:: the class name to use, if it can't be inferred by
  105. # camelizing the singular name
  106. # <tt>:per_page</tt>:: the maximum number of items to include in a
  107. # single page. Defaults to 10
  108. # <tt>:conditions</tt>:: optional conditions passed to Model.find(:all, *params) and
  109. # Model.count
  110. # <tt>:order</tt>:: optional order parameter passed to Model.find(:all, *params)
  111. # <tt>:order_by</tt>:: (deprecated, used :order) optional order parameter passed to Model.find(:all, *params)
  112. # <tt>:joins</tt>:: optional joins parameter passed to Model.find(:all, *params)
  113. # and Model.count
  114. # <tt>:join</tt>:: (deprecated, used :joins or :include) optional join parameter passed to Model.find(:all, *params)
  115. # and Model.count
  116. # <tt>:include</tt>:: optional eager loading parameter passed to Model.find(:all, *params)
  117. # and Model.count
  118. # <tt>:select</tt>:: :select parameter passed to Model.find(:all, *params)
  119. #
  120. # <tt>:count</tt>:: parameter passed as :select option to Model.count(*params)
  121. #
  122. # <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
  123. #
  124. def paginate(collection_id, options={})
  125. Pagination.validate_options!(collection_id, options, true)
  126. paginator_and_collection_for(collection_id, options)
  127. end
  128. # These methods become class methods on any controller
  129. module ClassMethods
  130. # Creates a +before_filter+ which automatically paginates an Active
  131. # Record model for all actions in a controller (or certain actions if
  132. # specified with the <tt>:actions</tt> option).
  133. #
  134. # +options+ are the same as PaginationHelper#paginate, with the addition
  135. # of:
  136. # <tt>:actions</tt>:: an array of actions for which the pagination is
  137. # active. Defaults to +nil+ (i.e., every action)
  138. def paginate(collection_id, options={})
  139. Pagination.validate_options!(collection_id, options, false)
  140. module_eval do
  141. before_filter :create_paginators_and_retrieve_collections
  142. OPTIONS[self] ||= Hash.new
  143. OPTIONS[self][collection_id] = options
  144. end
  145. end
  146. end
  147. def create_paginators_and_retrieve_collections #:nodoc:
  148. Pagination::OPTIONS[self.class].each do |collection_id, options|
  149. next unless options[:actions].include? action_name if
  150. options[:actions]
  151. paginator, collection =
  152. paginator_and_collection_for(collection_id, options)
  153. paginator_name = "@#{options[:singular_name]}_pages"
  154. self.instance_variable_set(paginator_name, paginator)
  155. collection_name = "@#{collection_id.to_s}"
  156. self.instance_variable_set(collection_name, collection)
  157. end
  158. end
  159. # Returns the total number of items in the collection to be paginated for
  160. # the +model+ and given +conditions+. Override this method to implement a
  161. # custom counter.
  162. def count_collection_for_pagination(model, options)
  163. model.count(:conditions => options[:conditions],
  164. :joins => options[:join] || options[:joins],
  165. :include => options[:include],
  166. :select => (options[:group] ? "DISTINCT #{options[:group]}" : options[:count]))
  167. end
  168. # Returns a collection of items for the given +model+ and +options[conditions]+,
  169. # ordered by +options[order]+, for the current page in the given +paginator+.
  170. # Override this method to implement a custom finder.
  171. def find_collection_for_pagination(model, options, paginator)
  172. model.find(:all, :conditions => options[:conditions],
  173. :order => options[:order_by] || options[:order],
  174. :joins => options[:join] || options[:joins], :include => options[:include],
  175. :select => options[:select], :limit => options[:per_page],
  176. :group => options[:group], :offset => paginator.current.offset)
  177. end
  178. protected :create_paginators_and_retrieve_collections,
  179. :count_collection_for_pagination,
  180. :find_collection_for_pagination
  181. def paginator_and_collection_for(collection_id, options) #:nodoc:
  182. klass = options[:class_name].constantize
  183. page = params[options[:parameter]]
  184. count = count_collection_for_pagination(klass, options)
  185. paginator = Paginator.new(self, count, options[:per_page], page)
  186. collection = find_collection_for_pagination(klass, options, paginator)
  187. return paginator, collection
  188. end
  189. private :paginator_and_collection_for
  190. # A class representing a paginator for an Active Record collection.
  191. class Paginator
  192. include Enumerable
  193. # Creates a new Paginator on the given +controller+ for a set of items
  194. # of size +item_count+ and having +items_per_page+ items per page.
  195. # Raises ArgumentError if items_per_page is out of bounds (i.e., less
  196. # than or equal to zero). The page CGI parameter for links defaults to
  197. # "page" and can be overridden with +page_parameter+.
  198. def initialize(controller, item_count, items_per_page, current_page=1)
  199. raise ArgumentError, 'must have at least one item per page' if
  200. items_per_page <= 0
  201. @controller = controller
  202. @item_count = item_count || 0
  203. @items_per_page = items_per_page
  204. @pages = {}
  205. self.current_page = current_page
  206. end
  207. attr_reader :controller, :item_count, :items_per_page
  208. # Sets the current page number of this paginator. If +page+ is a Page
  209. # object, its +number+ attribute is used as the value; if the page does
  210. # not belong to this Paginator, an ArgumentError is raised.
  211. def current_page=(page)
  212. if page.is_a? Page
  213. raise ArgumentError, 'Page/Paginator mismatch' unless
  214. page.paginator == self
  215. end
  216. page = page.to_i
  217. @current_page_number = has_page_number?(page) ? page : 1
  218. end
  219. # Returns a Page object representing this paginator's current page.
  220. def current_page
  221. @current_page ||= self[@current_page_number]
  222. end
  223. alias current :current_page
  224. # Returns a new Page representing the first page in this paginator.
  225. def first_page
  226. @first_page ||= self[1]
  227. end
  228. alias first :first_page
  229. # Returns a new Page representing the last page in this paginator.
  230. def last_page
  231. @last_page ||= self[page_count]
  232. end
  233. alias last :last_page
  234. # Returns the number of pages in this paginator.
  235. def page_count
  236. @page_count ||= @item_count.zero? ? 1 :
  237. (q,r=@item_count.divmod(@items_per_page); r==0? q : q+1)
  238. end
  239. alias length :page_count
  240. # Returns true if this paginator contains the page of index +number+.
  241. def has_page_number?(number)
  242. number >= 1 and number <= page_count
  243. end
  244. # Returns a new Page representing the page with the given index
  245. # +number+.
  246. def [](number)
  247. @pages[number] ||= Page.new(self, number)
  248. end
  249. # Successively yields all the paginator's pages to the given block.
  250. def each(&block)
  251. page_count.times do |n|
  252. yield self[n+1]
  253. end
  254. end
  255. # A class representing a single page in a paginator.
  256. class Page
  257. include Comparable
  258. # Creates a new Page for the given +paginator+ with the index
  259. # +number+. If +number+ is not in the range of valid page numbers or
  260. # is not a number at all, it defaults to 1.
  261. def initialize(paginator, number)
  262. @paginator = paginator
  263. @number = number.to_i
  264. @number = 1 unless @paginator.has_page_number? @number
  265. end
  266. attr_reader :paginator, :number
  267. alias to_i :number
  268. # Compares two Page objects and returns true when they represent the
  269. # same page (i.e., their paginators are the same and they have the
  270. # same page number).
  271. def ==(page)
  272. return false if page.nil?
  273. @paginator == page.paginator and
  274. @number == page.number
  275. end
  276. # Compares two Page objects and returns -1 if the left-hand page comes
  277. # before the right-hand page, 0 if the pages are equal, and 1 if the
  278. # left-hand page comes after the right-hand page. Raises ArgumentError
  279. # if the pages do not belong to the same Paginator object.
  280. def <=>(page)
  281. raise ArgumentError unless @paginator == page.paginator
  282. @number <=> page.number
  283. end
  284. # Returns the item offset for the first item in this page.
  285. def offset
  286. @paginator.items_per_page * (@number - 1)
  287. end
  288. # Returns the number of the first item displayed.
  289. def first_item
  290. offset + 1
  291. end
  292. # Returns the number of the last item displayed.
  293. def last_item
  294. [@paginator.items_per_page * @number, @paginator.item_count].min
  295. end
  296. # Returns true if this page is the first page in the paginator.
  297. def first?
  298. self == @paginator.first
  299. end
  300. # Returns true if this page is the last page in the paginator.
  301. def last?
  302. self == @paginator.last
  303. end
  304. # Returns a new Page object representing the page just before this
  305. # page, or nil if this is the first page.
  306. def previous
  307. if first? then nil else @paginator[@number - 1] end
  308. end
  309. # Returns a new Page object representing the page just after this
  310. # page, or nil if this is the last page.
  311. def next
  312. if last? then nil else @paginator[@number + 1] end
  313. end
  314. # Returns a new Window object for this page with the specified
  315. # +padding+.
  316. def window(padding=2)
  317. Window.new(self, padding)
  318. end
  319. # Returns the limit/offset array for this page.
  320. def to_sql
  321. [@paginator.items_per_page, offset]
  322. end
  323. def to_param #:nodoc:
  324. @number.to_s
  325. end
  326. end
  327. # A class for representing ranges around a given page.
  328. class Window
  329. # Creates a new Window object for the given +page+ with the specified
  330. # +padding+.
  331. def initialize(page, padding=2)
  332. @paginator = page.paginator
  333. @page = page
  334. self.padding = padding
  335. end
  336. attr_reader :paginator, :page
  337. # Sets the window's padding (the number of pages on either side of the
  338. # window page).
  339. def padding=(padding)
  340. @padding = padding < 0 ? 0 : padding
  341. # Find the beginning and end pages of the window
  342. @first = @paginator.has_page_number?(@page.number - @padding) ?
  343. @paginator[@page.number - @padding] : @paginator.first
  344. @last = @paginator.has_page_number?(@page.number + @padding) ?
  345. @paginator[@page.number + @padding] : @paginator.last
  346. end
  347. attr_reader :padding, :first, :last
  348. # Returns an array of Page objects in the current window.
  349. def pages
  350. (@first.number..@last.number).to_a.collect! {|n| @paginator[n]}
  351. end
  352. alias to_a :pages
  353. end
  354. end
  355. end
  356. end