Internals

To better understand how Will Paginate works, here is what the library does to hook into Rails. The main hook is the WillPaginate.enable method.

There is a plugin and gem version. The latter you should load explicitly with require 'will_paginate' in the environment.rb file. When you do that and ActiveRecord and ActionPack are present, the enable hook is called. The plugin version loads automatically via the same hook during the plugin load process.

ActiveRecord

First, WillPaginate::Finder is mixed into ActiveRecord::Base. That defines the paginate, paginate_by_sql and per_page (default: 30) methods in your models, and also hooks into method_missing to provide paginating finders like paginate_by_first_name. These dynamic finders internally use the paginate method with :finder parameter.

All paginating finders return a new WillPaginate::Collection instance (created from the result set); since it’s an Array subclass, it acts just like it when you use it later on.

Besides ActiveRecord::Base, the WillPaginate::Finder::ClassMethods module gets mixed in classes under ActiveRecord::Associations to provide the same pagination functionality to has_many, has_many :through and has_and_belongs_to_many associations.

ActionPack

To provide view helpers, WillPaginate::ViewHelpers module is included in ActionView::Base. The main view helper, will_paginate(), uses WillPaginate::LinkRenderer internally to render the pagination links. You can subclass it to make your own renderer.

Also, in Rails 2.0, a rescue rule gets added in ActionController:

ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found

This was added on March 3rd, 2008 and it makes sure that WillPaginate::InvalidPage errors result in HTTP 404 responses. Of course, you could use rescue_from in your controller to specify a custom action; for instance, you may redirect to page 1.

Last edited by mislav, 4 months ago
Versions: