Skip to content
Browse files

Implementing paginate in Mongoid::Document

  • Loading branch information...
1 parent 7c8fbf3 commit bedc7ab4af4869dd71271483612cd5289a3cc9d0 Lucas Souza committed Oct 20, 2011
View
1 lib/will_paginate_mongoid.rb
@@ -1,2 +1,3 @@
require "will_paginate_mongoid/version"
require "will_paginate_mongoid/mongoid_paginator"
+require "will_paginate_mongoid/engine"
View
10 lib/will_paginate_mongoid/engine.rb
@@ -0,0 +1,10 @@
+require 'rails'
+require 'mongoid'
+
+module WillPaginateMongoid
+ class Engine < ::Rails::Engine
+ initializer "including extensions" do
+ ::Mongoid::Document.send :include, WillPaginateMongoid::MongoidPaginator::Document
+ end
+ end
+end
View
28 lib/will_paginate_mongoid/mongoid_paginator.rb
@@ -1,7 +1,33 @@
module WillPaginateMongoid
+ DEFAULT_PER_PAGE = 10
+
module MongoidPaginator
+ class << self
+ def base_options(options)
+ options[:page] ||= 1
+ options[:per_page] ||= 10
+ options[:offset] = (options[:page].to_i - 1) * options[:per_page]
+ options
+ end
+
+ def fill_pager_with(medias, size, pager)
+ pager.replace medias.to_a
+ pager.total_entries = size
+ end
+ end
+
module Document
extend ActiveSupport::Concern
+
+ included do
+ def self.paginate(options = {})
+ options = MongoidPaginator.base_options options
+
+ WillPaginate::Collection.create(options[:page], options[:per_page]) do |pager|
+ MongoidPaginator.fill_pager_with self.skip(options[:offset]).limit(options[:per_page]), self.count, pager
+ end
+ end
+ end
end
end
-end
+end
View
23 spec/integration/mongoid_paginator_spec.rb
@@ -9,5 +9,26 @@ class Game
end
describe :paginate do
+ before :each do
+ @games = 30.times.map do |i|
+ Game.create :title => "title_#{i}"
+ end
+ end
+
+ context "when called in a Mongoid::Document" do
+ context "and parameters is given" do
+ subject { Game.paginate :page => 2, :per_page => 10 }
+ it { should be_a_instance_of WillPaginate::Collection }
+ its(:to_a) { should == @games[10..19] }
+ its(:total_entries) { should == Game.count }
+ end
+
+ context "and parameters is not given" do
+ subject { Game.paginate }
+ it { should be_a_instance_of WillPaginate::Collection }
+ its(:to_a) { should == @games[0..9] }
+ its(:total_entries) { should == 30 }
+ end
+ end
end
-end
+end

0 comments on commit bedc7ab

Please sign in to comment.
Something went wrong with that request. Please try again.