Pagination in Merb
Pagination is one of those things that almost every site needs and for which there is absolutely no glory. Boring stuff, pagination, the Edmonton of software development. Which might explain why, when I needed to figure out how to paginate in Merb a little while ago, it was so difficult to find clear instructions on how to do so. When you find yourself in pagination you do what you have to do and then move on, with nary a glance back (apologies to both my readers in Edmonton, but you know I’m right.)
Oh sure, lots of posts on the web say “use Lori Holden’s dm-is-paginated with merb-pagination” but none say quite exactly how. And while I’m fully willing to concede I may be a little thick sometimes I found the examples on her pages somewhat under-enlightening. Hints of light bulbs but no switches, as it were.
So, embarking under the assumption that both dm-is-paginated and merb-pagination are installed on your system, here’s how I got pagination working with Merb. In this example I’ll use my DbAdminLog class as an example.
First, make sure you have the dependencies declared in dependencies.rb. At the time of this writing, these were:
dependency "merb-pagination", "0.0.1" dependency "dm-is-paginated", "0.0.1"
In the DbAdminLog model, I added this line underneath my property definitions and validations:
is_paginated
This provides the pagination methods to the model necessary elsewhere. If you don’t add this line, no pagination for you, which is funny because it isn’t mentioned anywhere on the example pages linked above ( “…on public display in the local planning department for months, locked in a filing cabinet in the darkened cellar behind a sign that says, ‘Beware of the Leopard’”.)
In the DbAdminLogs controller I added the following to the index() method:
def index @current_page = ( params[:page] && ( params[:page].to_i > 0 ) ) ? params[:page].to_i : 1 @page_count, @db_admin_logs = DbAdminLog.paginated(rder => [ :created_at.desc ], :conditions => cond, :page => @current_page, :per_page => 20 ) display @db_admin_logs end
The first line figures out which page of results we’re displaying, based on the GET parameter supplied (or not supplied, in the case of the default “1″.) The second line is the pagination magic in which I define the order to be displayed (they’re log files, so LIFO), any filtering conditions via the cond variable (if you want every record unfiltered you can leave :conditions out or replace cond with ["1"]), the page number and the number of entries to be displayed per page.
(For extra credit, swap out the && with andand and be 1337.)
That’s the controller.
The view is pleasantly straightforward. In index.html.haml I added the following at the bottom below the display code:
= paginate( @current_page, @page_count, :inner_window => 5 )
And there you have it: merb pagination.
Comments Off
