Module: Mongoid::Pagination::ClassMethods
- Defined in:
- lib/mongoid/pagination.rb
Instance Method Summary collapse
- #page_size ⇒ Object
- #page_size=(page_size) ⇒ Object
- #paginate(opts = {}) ⇒ Object
- #paginate_offset(opts = {}) ⇒ Object
- #paginated_collection ⇒ Object
-
#paginated_criteria(opts = {}) ⇒ Mongoid::Criteria
Paginate the results.
-
#per_page(page_limit = page_size) ⇒ Mongoid::Criteria
Limit the result set.
- #preload(args) ⇒ Object
Instance Method Details
#page_size ⇒ Object
7 8 9 |
# File 'lib/mongoid/pagination.rb', line 7 def page_size @page_size || 25 end |
#page_size=(page_size) ⇒ Object
11 12 13 |
# File 'lib/mongoid/pagination.rb', line 11 def page_size=(page_size) @page_size = page_size end |
#paginate(opts = {}) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/mongoid/pagination.rb', line 30 def paginate(opts = {}) criteria = paginated_criteria(opts) limit = criteria.[:limit] criteria.[:limit] += 1 over_fetched_collection = criteria.to_a has_more_results = over_fetched_collection.size > limit over_fetched_collection.pop if has_more_results @paginated_collection = ::Mongoid::Pagination::Collection.new(over_fetched_collection) @paginated_collection.current_offset = criteria.[:skip] @paginated_collection.current_page_size = limit @paginated_collection.has_more_results = has_more_results preload(opts[:eager_load]) if opts[:eager_load].present? @paginated_collection end |
#paginate_offset(opts = {}) ⇒ Object
69 70 71 72 73 74 75 |
# File 'lib/mongoid/pagination.rb', line 69 def paginate_offset(opts = {}) case when opts[:page] && (page = opts[:page].to_i) > 0 then (page - 1) * (opts[:limit] || page_size).to_i when opts[:offset] && (offset = opts[:offset].to_i) >= 0 then offset else 0 end end |
#paginated_collection ⇒ Object
77 78 79 |
# File 'lib/mongoid/pagination.rb', line 77 def paginated_collection @paginated_collection end |
#paginated_criteria(opts = {}) ⇒ Mongoid::Criteria
Paginate the results
23 24 25 26 27 28 |
# File 'lib/mongoid/pagination.rb', line 23 def paginated_criteria(opts = {}) limit = (opts[:limit] || page_size).to_i offset = paginate_offset(opts) per_page(limit).offset(offset) end |
#per_page(page_limit = page_size) ⇒ Mongoid::Criteria
Limit the result set
65 66 67 |
# File 'lib/mongoid/pagination.rb', line 65 def per_page(page_limit = page_size) limit(page_limit.to_i) end |
#preload(args) ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/mongoid/pagination.rb', line 51 def preload(args) return unless args.present? && @paginated_collection.present? relations.select { |k,v| args.map(&:to_s).include?(k) }.each_pair do |name,| field_key = .key ids = @paginated_collection.map { |c| c.send(field_key.to_sym) }.compact .class_name.constantize.any_in(_id: ids).to_a if ids.present? end end |