From 873dcf9a90527307e8d9d1b6b90b442682ebe292 Mon Sep 17 00:00:00 2001 From: Bryan Ricker Date: Mon, 10 Dec 2012 17:51:44 -0800 Subject: [PATCH] Fix coercion error when offset_value is nil This commit does two things: * Adds `.offset(0)` when limit is set to `nil` for consistency * Force-returns `1` for `#total_pages` and `#current_page` when using `per(nil)`. This avoid "Cannot coerce nil into Fixnum" errors, and will also prevent "ZeroDivisionError" if `limit_value` is ever typecast using `to_i`. --- lib/kaminari/models/page_scope_methods.rb | 5 ++++- spec/models/active_record/scopes_spec.rb | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/kaminari/models/page_scope_methods.rb b/lib/kaminari/models/page_scope_methods.rb index ada88a2..e758ac7 100644 --- a/lib/kaminari/models/page_scope_methods.rb +++ b/lib/kaminari/models/page_scope_methods.rb @@ -4,7 +4,7 @@ module Kaminari # Model.page(3).per(10) def per(num) if num.nil? - limit(nil) + limit(nil).offset(0) elsif (n = num.to_i) <= 0 self elsif max_per_page && max_per_page < n @@ -20,6 +20,8 @@ module Kaminari # Total number of pages def total_pages + return 1 if limit_value.nil? + total_pages_count = (total_count.to_f / limit_value).ceil if max_pages.present? && max_pages < total_pages_count max_pages @@ -32,6 +34,7 @@ module Kaminari # Current page number def current_page + return 1 if limit_value.nil? (offset_value / limit_value) + 1 end diff --git a/spec/models/active_record/scopes_spec.rb b/spec/models/active_record/scopes_spec.rb index f0cc589..31dd3c8 100644 --- a/spec/models/active_record/scopes_spec.rb +++ b/spec/models/active_record/scopes_spec.rb @@ -123,6 +123,11 @@ if defined? ActiveRecord subject { model_class.page } its(:total_pages) { should == 4 } end + + context "with per(nil)" do + subject { model_class.page.per(nil) } + its(:total_pages) { should == 1 } + end end @@ -136,6 +141,11 @@ if defined? ActiveRecord subject { model_class.page(2).per 3 } its(:current_page) { should == 2 } end + + context "with per(nil)" do + subject { model_class.page.per(nil) } + its(:current_page) { should == 1 } + end end describe '#first_page?' do