File: mongoid.rb

package info (click to toggle)
ruby-will-paginate 3.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 444 kB
  • sloc: ruby: 2,940; sh: 50; makefile: 2
file content (48 lines) | stat: -rw-r--r-- 1,159 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
require 'mongoid'
require 'will_paginate/collection'

module WillPaginate
  module Mongoid
    module CriteriaMethods
      def paginate(options = {})
        extend CollectionMethods
        @current_page = WillPaginate::PageNumber(options[:page] || @current_page || 1)
        @page_multiplier = current_page - 1
        @total_entries = options.delete(:total_entries)

        pp = (options[:per_page] || per_page || WillPaginate.per_page).to_i
        limit(pp).skip(@page_multiplier * pp)
      end

      def per_page(value = :non_given)
        if value == :non_given
          options[:limit] == 0 ? nil : options[:limit] # in new Mongoid versions a nil limit is saved as 0
        else
          limit(value)
        end
      end

      def page(page)
        paginate(:page => page)
      end
    end

    module CollectionMethods
      attr_reader :current_page

      def total_entries
        @total_entries ||= count
      end

      def total_pages
        (total_entries / per_page.to_f).ceil
      end

      def offset
        @page_multiplier * per_page
      end
    end

    ::Mongoid::Criteria.send(:include, CriteriaMethods)
  end
end