→ Paginate Anything

10 February 2008

We just added pagination on commit lists to GitHub. You can see it in action at Dr Nic’s two_point_ooh branch of the Rails TextMate bundle.

The thing is, we don’t use SQL to store our commits. We pull them straight from Git. Which means if we want to paginate them, it’s not as simple as a Commit.paginate() call.

Fortunately for us, will_paginate plays nicely with arbitrary collections (as long as you know the total number of entries).

In our Repository model we’ve got this:

def paged_commits(tree_name, page, per_page = 30)
  page    = (page || 1).to_i
  total   = git.commit_count(tree_name)
  offset  = (page - 1) * per_page
  commits = WillPaginate::Collection.new(page, per_page, total)
  commits.replace git.commits(tree_name, per_page, offset)
end

In our controller, we call it thusly:

@commits = current_repository.paged_commits(tree_name, params[:page])

Then, of course, we top it off in the view:

<%= will_paginate @commits %>

So fresh and so clean.