Thursday, April 23, 2009

Pagination, Page 2

‹prev | My Chain | next›

Continuing work on pagination, I need to get page links working. The place to do this is in a pagination helper. I will stick close to the couchdb-lucene API by passing in three arguments to the pagination helper: the record offset, the page size (called limit by couchdb-lucene), and the total number of records.

My first two examples:
describe "pagination" do
it "should have a link to other pages" do
pagination(0, 20, 41).
should have_selector("a", :content => "2")
end
it "should have 3 pages, when results.size > 2 * page size" do
pagination(0, 20, 41).
should have_selector("a", :content => "3")
end
end
Writing just enough code to implement these two examples, I end up with this:
    def pagination(skip, limit, total)
total_pages = (total + limit - 1) / limit

links = (1..total_pages).map do |page|
%Q|<a href="">#{page}</a>|
end

%Q|<div class="pagination">#{links.join}</div>|
end
The next example I write explores the boundary condition of the total number of results being exactly divisible by the page size:
  it "should have only 2 pages, when results.size == 2 * page size" do
pagination(0, 20, 40).
should_not have_selector("a", :content => "3")
end
When I run it, I get a failure indicating that I don't quite have my boundaries set correctly:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/eee_helpers_spec.rb
...........F

1)
'pagination should have only 2 pages, when results.size == 2 * page size' FAILED
expected following output to omit a <a>3</a>:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><div class="pagination">
<a href="">1</a><a href="">2</a><a href="">3</a>
</div></body></html>
./spec/eee_helpers_spec.rb:82:

Finished in 0.014629 seconds

12 examples, 1 failure
Ah, a fence post is being counted. It can be removed by subtracting 1:
    def pagination(skip, limit, total)
total_pages = (total + limit - 1) / limit

links = (1..total_pages).map do |page|
%Q|<a href="">#{page}</a>|
end

%Q|<div class="pagination">#{links.join}</div>|
end
I notice that I have no links in those hrefs. That will have to wait until tomorrow though.
(commit)

No comments:

Post a Comment