better links for search result pagination

closes #69
This commit is contained in:
joshua stein 2015-01-11 12:59:06 -06:00
parent ce8eb45008
commit d01e9f3c3f
4 changed files with 75 additions and 7 deletions

View File

@ -591,18 +591,22 @@ div.page_link_buttons {
font-weight: bold;
margin-top: 2em;
}
div.page_link_buttons a {
color: #666;
div.page_link_buttons a,
div.page_link_buttons span {
border: 1px solid #d0d0d0;
background-color: #f3f3f3;
color: #666;
padding: 0.25em 0.5em;
font-weight: bold;
text-decoration: none;
margin-left: 0.5em;
}
div.page_link_buttons a.cur {
div.page_link_buttons a.cur,
div.page_link_buttons span {
background-color: transparent;
border-color: transparent;
margin-left: 0.25em;
padding-right: 0.25em;
}

View File

@ -1,4 +1,6 @@
module ApplicationHelper
MAX_PAGES = 15
def errors_for(object, message=nil)
html = ""
unless object.errors.blank?
@ -22,4 +24,40 @@ module ApplicationHelper
raw(label_tag(nil, ago, :title => time.strftime("%F %T %z")))
end
def page_numbers_for_pagination(max, cur)
if max <= MAX_PAGES
return (1 .. max).to_a
end
pages = (cur - (MAX_PAGES / 2) + 1 .. cur + (MAX_PAGES / 2) - 1).to_a
while pages[0] < 1
pages.push (pages.last + 1)
pages.shift
end
while pages.last > max
if pages[0] > 1
pages.unshift (pages[0] - 1)
end
pages.pop
end
if pages[0] != 1
if pages[0] != 2
pages.unshift "..."
end
pages.unshift 1
end
if pages.last != max
if pages.last != max - 1
pages.push "..."
end
pages.push max
end
pages
end
end

View File

@ -72,10 +72,14 @@
<div class="page_link_buttons">
Page:
<% 1.upto(@search.page_count) do |p| %>
<a href="/search?<%= raw(@search.to_url_params) %>&amp;page=<%= p
%>" class="<%= @search.page == p ? "cur" : "" %>"><%= p
%></a>
<% page_numbers_for_pagination(@search.page_count, @search.page).each do |p| %>
<% if p.is_a?(Integer) %>
<a href="/search?<%= raw(@search.to_url_params) %>&amp;page=<%= p
%>" class="<%= @search.page == p ? "cur" : "" %>"><%= p
%></a>
<% else %>
<span>...</span>
<% end %>
<% end %>
</div>
<% end %>

View File

@ -0,0 +1,22 @@
require "spec_helper"
describe ApplicationHelper do
describe "#page_numbers_for_pagination" do
it "returns the right number of pages" do
helper.page_numbers_for_pagination(10, 1).should ==
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
helper.page_numbers_for_pagination(20, 1).should ==
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "...", 20 ]
helper.page_numbers_for_pagination(25, 1).should ==
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "...", 25 ]
helper.page_numbers_for_pagination(25, 10).should ==
[ 1, "...", 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, "...", 25 ]
helper.page_numbers_for_pagination(25, 20).should ==
[ 1, "...", 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
end
end
end