1class ApiPaginationLinksPresenter
 
2  include Rails.application.routes.url_helpers
 
3
 
4  # results should be a Browseable::Search instance that
 
5  # exposes the attributes delegated to it below
  • Complexity 1 » saikuro
6  def initialize(results, params)
 
7    @results, @params = results, params
 
8  end
 
 9
  • Complexity 1 » saikuro
10  def serialize
 
11    {
 
12      first: first_url,
 
13      last: last_url,
 
14      next: next_url,
 
15      prev: prev_url
 
16    }
 
17  end
 
 
19  private
 
 
21  attr_reader :results, :params
 
 
23  delegate :total_pages, :first_page?, :second_page?, :last_page?, to: :results
 
 
25  # Sense check that the current page cannot be greater than the total number of pages
  • Complexity 1 » saikuro
26  def current_page
 
27    [results.current_page, results.total_pages].min
 
28  end
 
  • Complexity 1 » saikuro
30  def first_url
 
31    url_for url_params
 
32  end
 
  • Complexity 2 » saikuro
34  def last_url
 
35    # If there are no results then the first_page == last_page
 
36    if total_pages == 1
 
37      first_url
 
38    else
 
39      url_for url_params.merge(page: total_pages)
 
40    end
 
41  end
 
  • Complexity 2 » saikuro
43  def next_url
 
44    unless results.last_page?
 
45      url_for url_params.merge(page: current_page + 1)
 
46    else
 
47      nil
 
48    end
 
49  end
 
  • Complexity 4 » saikuro
51  def prev_url
 
52    # first page of results does not need the :page param to improve caching
 
53    return first_url if second_page?
 
 
55    # use the last_url if we have paged off the end of the results
 
56    return last_url if results.current_page > total_pages
 
 
58    # only supply a link if there is a page of results before the current_page
 
59    if current_page > 1
 
60      url_for url_params.merge(page: current_page - 1)
 
61    else
 
62      nil
 
63    end
 
64  end
 
  • Complexity 1 » saikuro
66  def url_params
 
67    params.slice(*api_links_allowed_components)
 
68  end
 
  • Complexity 1 » saikuro
70  def api_links_allowed_components
 
71    [:protocol, :host, :port, :controller, :action, :q, :count, :state, :format]
 
72  end
 
73end