Module: Mongoid::Pagination::ClassMethods

Defined in:
lib/mongoid/pagination.rb

Instance Method Summary collapse

Instance Method Details

#page_sizeObject



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.options[:limit]
  criteria.options[: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.options[: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_collectionObject



77
78
79
# File 'lib/mongoid/pagination.rb', line 77

def paginated_collection
  @paginated_collection
end

#paginated_criteria(opts = {}) ⇒ Mongoid::Criteria

Paginate the results

Parameters:

  • opts (Hash) (defaults to: {})
  • [Integer] (Hash)

    a customizable set of options

Returns:

  • (Mongoid::Criteria)


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

Parameters:

  • page_limit (Integer) (defaults to: page_size)

    the max number of results to return

Returns:

  • (Mongoid::Criteria)


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,meta|
    field_key = meta.key
    ids = @paginated_collection.map { |c| c.send(field_key.to_sym) }.compact
    meta.class_name.constantize.any_in(_id: ids).to_a if ids.present?
  end
end