Permalink
Browse files

validate SQL offset to fit in BIGINT rather than page number

  • Loading branch information...
1 parent 58cea62 commit 5c09d09536c82b68dfeb78e5359d9518dd6591f0 @mislav committed Aug 2, 2011
Showing with 18 additions and 21 deletions.
  1. +14 −14 lib/will_paginate/collection.rb
  2. +4 −7 test/collection_test.rb
@@ -20,15 +20,21 @@ class InvalidPage < ArgumentError
# a value bigger than this would result in invalid SQL queries
BIGINT = 9223372036854775807
- def self.validate(value)
- num = value.to_i
- if num < 1 or num > BIGINT then yield num
- else num
- end
+ def self.validate(page_value, per_page_value)
+ page = page_value.to_i
+ raise self.new(page_value, page) if page < 1
+ per_page = per_page_value.to_i
+ offset = (page - 1) * per_page
+ raise self, "invalid offset: #{offset.inspect}" if offset < 0 or offset > BIGINT
+ [page, per_page]
end
- def initialize(page, page_num)
- super "#{page.inspect} given as value, which translates to '#{page_num}' as page number"
+ def initialize(value, page_num = nil)
+ if page_num
+ super "#{value.inspect} given as value, which translates to '#{page_num}' as page number"
+ else
+ super value
+ end
end
end
@@ -55,13 +61,7 @@ class Collection < Array
# is best to do lazy counting; in other words, count *conditionally* after
# populating the collection using the +replace+ method.
def initialize(page, per_page, total = nil)
- @current_page = InvalidPage.validate(page) do |num|
- raise InvalidPage.new(page, num)
- end
- @per_page = InvalidPage.validate(per_page) do |num|
- raise ArgumentError, "invalid :per_page value: #{per_page.inspect}"
- end
-
+ @current_page, @per_page = InvalidPage.validate(page, per_page)
self.total_entries = total if total
end
View
@@ -112,19 +112,16 @@ def test_guessing_total_count
end
def test_invalid_page
- bad_inputs = [0, -1, nil, '', 9223372036854775808, 'Schnitzel']
+ bad_inputs = [0, -1, nil, '', 'Schnitzel']
bad_inputs.each do |bad|
assert_raise(WillPaginate::InvalidPage) { create bad }
end
end
- def test_invalid_per_page
- bad_inputs = [0, -1, 9223372036854775808, 'Schnitzel']
-
- bad_inputs.each do |bad|
- assert_raise(ArgumentError) { create(1, bad) }
- end
+ def test_invalid_offset
+ error = assert_raise(WillPaginate::InvalidPage) { create(307445734561825862, 30) }
+ assert_equal "invalid offset: 9223372036854775830", error.message
end
def test_page_count_was_removed

0 comments on commit 5c09d09

Please sign in to comment.