Module: JsonApiPaginationLinks

Extended by:
ActiveSupport::Concern
Included in:
RxController, SMController
Defined in:
app/controllers/concerns/json_api_pagination_links.rb

Instance Method Summary collapse

Instance Method Details

#base_pathObject (private)



46
47
48
# File 'app/controllers/concerns/json_api_pagination_links.rb', line 46

def base_path
  "#{Rails.application.config.protocol}://#{Rails.application.config.hostname}"
end

#build_page_url(page_number, per_page) ⇒ Object (private)



35
36
37
38
39
40
41
42
43
44
# File 'app/controllers/concerns/json_api_pagination_links.rb', line 35

def build_page_url(page_number, per_page)
  url_params = {
    page: page_number,
    per_page:,
    query_parameters: request.query_parameters
  }
  path_partial = URI.parse(request.original_url).path
  url = "#{base_path}#{path_partial}?#{url_params.to_query}"
  URI.parse(url).to_s
end


29
30
31
32
33
# File 'app/controllers/concerns/json_api_pagination_links.rb', line 29

def next_link(current_page, per_page, total_pages)
  return nil if current_page >= total_pages

  build_page_url(current_page + 1, per_page)
end


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

def pagination_links(collection)
  total_size = collection.try(:size) || collection.data.size
  per_page = pagination_params[:per_page].try(:to_i) || total_size
  current_page = pagination_params[:page].try(:to_i) || 1
  total_pages = (total_size.to_f / per_page).ceil

  {
    self: build_page_url(current_page, per_page),
    first: build_page_url(1, per_page),
    prev: prev_link(current_page, per_page),
    next: next_link(current_page, per_page, total_pages),
    last: build_page_url(total_pages, per_page)
  }
end


23
24
25
26
27
# File 'app/controllers/concerns/json_api_pagination_links.rb', line 23

def prev_link(current_page, per_page)
  return nil if current_page <= 1

  build_page_url(current_page - 1, per_page)
end