Module: EIVO::Concerns::Pagination

Extended by:
ActiveSupport::Concern
Included in:
Resources
Defined in:
app/controllers/eivo/concerns/pagination.rb

Instance Method Summary collapse

Instance Method Details

#paginate(collection, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'app/controllers/eivo/concerns/pagination.rb', line 8

def paginate(collection, options = {})
  unless ::ActiveModel::Type::Boolean.new.cast(params[:pagination]) == false
    limit = 50
    if params[:limit]
      limit = [[params[:limit].to_i, 1].max, 500].min
    end

    collection = collection.page(params[:page]).per(limit)
    @serializer_options.merge!(pagination_options(collection))
  end

  collection
end

#pagination_options(collection) ⇒ Object



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
49
50
51
52
53
54
# File 'app/controllers/eivo/concerns/pagination.rb', line 22

def pagination_options(collection)
  options = {
    is_collection: true,
    links: {
      self: url_for(params.to_unsafe_h.merge(page: collection.current_page)),
      first: url_for(params.to_unsafe_h.merge(page: 1)),
    }
  }

  # avoid count request on large table
  if params[:pagination] == 'infinite'
    options[:links][:next] = url_for(params.to_unsafe_h.merge(page: collection.current_page + 1))

    if !collection.first_page?
      options[:links][:prev] = url_for(params.to_unsafe_h.merge(page: collection.current_page - 1))
    end
  else
    options[:links][:last] = url_for(params.to_unsafe_h.merge(page: collection.total_pages))
    options[:meta] = {
      total: collection.total_count,
      pages: collection.total_pages
    }

    if !collection.out_of_range? && !collection.last_page?
      options[:links][:next] = url_for(params.to_unsafe_h.merge(page: collection.next_page))
    end
    if !collection.out_of_range? && !collection.first_page?
      options[:links][:prev] = url_for(params.to_unsafe_h.merge(page: collection.prev_page))
    end
  end

  options
end