Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/geared_pagination/portions/portion_at_offset.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ def limit
end

def offset
(page_number - 1).times.sum { |index| ratios[index + 1] }
variable = [(page_number - 1), ratios.size - 1].min.times.sum { |index| ratios[index + 1] }
fixed = [page_number - ratios.size, 0].max * ratios.fixed

variable + fixed
end

def next_param(*)
Expand Down
12 changes: 10 additions & 2 deletions lib/geared_pagination/ratios.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@ class Ratios
DEFAULTS = [ 15, 30, 50, 100 ]

def initialize(ratios = nil)
@ratios = Array(ratios || DEFAULTS)
@ratios = Array(ratios || DEFAULTS).map(&:to_i)
end

def [](page_number)
@ratios[page_number - 1] || @ratios.last
@ratios[page_number - 1] || fixed
end

def cache_key
@ratios.join('-')
end

def size
@ratios.size
end

def fixed
@ratios.last
end
end
end
3 changes: 3 additions & 0 deletions test/controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ class GearedPagination::ControllerTest < ActionController::TestCase
assert_equal etag_for("placeholder", "page/1:1-2"), response.etag
etag_before_gearing_change = response.etag

get :index, params: { page: 2, per_page: [ 1, 2 ] }
assert_equal etag_for("placeholder", "page/2:1-2"), response.etag

get :index, params: { page: 1, per_page: [ 1, 2 ] }
assert_equal etag_before_gearing_change, response.etag

Expand Down
3 changes: 3 additions & 0 deletions test/portion_at_offset_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ class GearedPagination::PortionAtOffsetTest < ActiveSupport::TestCase
assert_equal 0, GearedPagination::PortionAtOffset.new(page_number: 1).offset
assert_equal GearedPagination::Ratios::DEFAULTS.first, GearedPagination::PortionAtOffset.new(page_number: 2).offset
assert_equal GearedPagination::Ratios::DEFAULTS.first + GearedPagination::Ratios::DEFAULTS.second, GearedPagination::PortionAtOffset.new(page_number: 3).offset
assert_equal 4.times.sum { |index| GearedPagination::Ratios::DEFAULTS[index] || GearedPagination::Ratios::DEFAULTS.last }, GearedPagination::PortionAtOffset.new(page_number: 5).offset
assert_equal 5.times.sum { |index| GearedPagination::Ratios::DEFAULTS[index] || GearedPagination::Ratios::DEFAULTS.last }, GearedPagination::PortionAtOffset.new(page_number: 6).offset
assert_equal 9.times.sum { |index| GearedPagination::Ratios::DEFAULTS[index] || GearedPagination::Ratios::DEFAULTS.last }, GearedPagination::PortionAtOffset.new(page_number: 10).offset
end

test "limit" do
Expand Down