Module: APIResourcePaginatable::HelperMethods

Defined in:
app/api/concerns/api_resource_paginatable.rb

Instance Method Summary collapse

Instance Method Details

#pageObject Also known as: current_page

Getter for the current page


96
97
98
# File 'app/api/concerns/api_resource_paginatable.rb', line 96

def page
  @page
end

#pagination(items_count, default_per_page: 20, maxium_per_page: 100, set_link_header: true) ⇒ Object


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'app/api/concerns/api_resource_paginatable.rb', line 62

def pagination(items_count, default_per_page: 20, maxium_per_page: 100, set_link_header: true)
  items_count = items_count.count if items_count.respond_to? :count

  @per_page = (params[:per_page] || default_per_page).to_i
  @per_page = maxium_per_page if @per_page > maxium_per_page
  @per_page = 1 if @per_page < 1

  items_count = 1 if items_count < 1
  pages_count = (items_count.to_f / @per_page).ceil
  pages_count = 1 if pages_count < 1

  @page = (params[:page] || 1).to_i
  @page = pages_count if @page > pages_count
  @page = 1 if @page < 1

  link_headers ||= []

  if current_page < pages_count
    link_headers << "<#{request.url.add_or_replace_uri_param(:page, current_page + 1)}>; rel=\"next\""
    link_headers << "<#{request.url.add_or_replace_uri_param(:page, pages_count)}>; rel=\"last\""
  end
  if current_page > 1
    link_headers << "<#{request.url.add_or_replace_uri_param(:page, (current_page > pages_count ? pages_count : current_page - 1))}>; rel=\"prev\""
    link_headers << "<#{request.url.add_or_replace_uri_param(:page, 1)}>; rel=\"first\""
  end

  link_header = link_headers.join(', ')

  header 'Link', link_header if set_link_header

  link_header
end

#per_pageObject Also known as: page_with

Getter for per_page


103
104
105
# File 'app/api/concerns/api_resource_paginatable.rb', line 103

def per_page
  @per_page
end