From 88c163eb0636cc416f4f8d79ddc28abbe4e7e31d Mon Sep 17 00:00:00 2001 From: aptx4869 Date: Thu, 12 Dec 2013 10:53:14 +0800 Subject: [PATCH] Add support for mongoid max_scan option respect the max_scan option in criteria cache the total_count in the collection instance prevent hitting db again in the same instance --- .../models/mongoid_criteria_methods.rb | 12 ++++- spec/models/mongoid/mongoid_spec.rb | 54 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/lib/kaminari/models/mongoid_criteria_methods.rb b/lib/kaminari/models/mongoid_criteria_methods.rb index 5fc4f64..1310ea5 100644 --- a/lib/kaminari/models/mongoid_criteria_methods.rb +++ b/lib/kaminari/models/mongoid_criteria_methods.rb @@ -9,7 +9,17 @@ module Kaminari end def total_count #:nodoc: - embedded? ? unpage.length : length + @total_count ||= + if embedded? + unpage.count + else + counter_result = count + if options[:max_scan] and options[:max_scan] < counter_result + options[:max_scan] + else + counter_result + end + end end private diff --git a/spec/models/mongoid/mongoid_spec.rb b/spec/models/mongoid/mongoid_spec.rb index 1b6af0b..e7e311b 100644 --- a/spec/models/mongoid/mongoid_spec.rb +++ b/spec/models/mongoid/mongoid_spec.rb @@ -8,6 +8,60 @@ if defined? Mongoid end end + describe 'max_scan', :if => Mongoid::VERSION >= '3' do + context 'less than total' do + context 'page 1' do + subject { User.max_scan(20).page 1 } + it { should be_a Mongoid::Criteria } + its(:current_page) { should == 1 } + its(:prev_page) { should be_nil } + its(:next_page) { should be_nil } + its(:limit_value) { should == 25 } + its(:total_pages) { should == 1 } + its(:total_count) { should == 20 } + it { should skip(0) } + end + + context 'page 2' do + subject { User.max_scan(30).page 2 } + it { should be_a Mongoid::Criteria } + its(:current_page) { should == 2 } + its(:prev_page) { should == 1 } + its(:next_page) { should be_nil } + its(:limit_value) { should == 25 } + its(:total_pages) { should == 2 } + its(:total_count) { should == 30 } + it { should skip 25 } + end + end + + context 'more than total' do + context 'page 1' do + subject { User.max_scan(60).page 1 } + it { should be_a Mongoid::Criteria } + its(:current_page) { should == 1 } + its(:prev_page) { should be_nil } + its(:next_page) { should == 2 } + its(:limit_value) { should == 25 } + its(:total_pages) { should == 2 } + its(:total_count) { should == 41 } + it { should skip(0) } + end + + context 'page 2' do + subject { User.max_scan(60).page 2 } + it { should be_a Mongoid::Criteria } + its(:current_page) { should == 2 } + its(:prev_page) { should == 1 } + its(:next_page) { should be_nil } + its(:limit_value) { should == 25 } + its(:total_pages) { should == 2 } + its(:total_count) { should == 41 } + it { should skip 25 } + end + end + end + describe '#page' do context 'page 1' do