Module: Upfluence::Mixin::Pagination

Defined in:
lib/upfluence/mixin/pagination.rb

Constant Summary collapse

DEFAULT_PAGE =
1
DEFAULT_PER_PAGE =
12
MAX_PER_PAGE =
200

Instance Method Summary collapse

Instance Method Details

#guess_per_pageObject



37
38
39
40
41
42
43
# File 'lib/upfluence/mixin/pagination.rb', line 37

def guess_per_page
  return params[:per_page].to_i if params[:per_page].present?

  return default_per_page if methods.include?(:default_per_page)

  DEFAULT_PER_PAGE
end

#pageObject



26
27
28
# File 'lib/upfluence/mixin/pagination.rb', line 26

def page
  [params[:page].to_i, DEFAULT_PAGE].max
end

#paginated_entitiesObject



12
13
14
15
16
# File 'lib/upfluence/mixin/pagination.rb', line 12

def paginated_entities
  @paginated_entities ||= paginated_model.limit(per_page).offset(
    (page - 1) * per_page
  ).to_a
end

#paginated_entities=(v) ⇒ Object



18
19
20
# File 'lib/upfluence/mixin/pagination.rb', line 18

def paginated_entities=(v)
  @paginated_entities = v
end

#paginated_modelObject

Raises:

  • (NotImplementedError)


8
9
10
# File 'lib/upfluence/mixin/pagination.rb', line 8

def paginated_model
  raise NotImplementedError
end

#paginated_totalObject



22
23
24
# File 'lib/upfluence/mixin/pagination.rb', line 22

def paginated_total
  paginated_model.count
end

#per_pageObject



30
31
32
33
34
35
# File 'lib/upfluence/mixin/pagination.rb', line 30

def per_page
  [
    [0, guess_per_page].max,
    MAX_PER_PAGE
  ].min
end

#respond_with_pagination(args = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/upfluence/mixin/pagination.rb', line 51

def respond_with_pagination(args = {})
  respond_with(
    args[:payload] || paginated_entities,
    args.merge(
      meta: {
        total: paginated_total,
        total_pages: total_pages,
        per_page: per_page
      }
    ) { |_, x, y| x.merge(y) }
  )
end

#total_pagesObject



45
46
47
48
49
# File 'lib/upfluence/mixin/pagination.rb', line 45

def total_pages
  return paginated_total if per_page <= 1

  (paginated_total.to_f / per_page.to_f).ceil
end