Module: Wiq::Pagination

Defined in:
lib/wiq/pagination.rb

Overview

Parses the WIQ pagination headers:

Link: <https://host/api/v1/foo?page=2>; rel="next", <...>; rel="last"
TotalCount: 123

Class Method Summary collapse

Class Method Details

.next_url(link_header) ⇒ Object



29
30
31
# File 'lib/wiq/pagination.rb', line 29

def next_url(link_header)
  parse_link(link_header)["next"]
end

Returns { “next” => “…url…”, “prev” => “…”, “first” => “…”, “last” => “…” }.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/wiq/pagination.rb', line 13

def parse_link(header)
  return {} if header.nil? || header.empty?

  header.split(",").each_with_object({}) do |part, acc|
    url_part, *params = part.split(";").map(&:strip)
    next unless url_part&.start_with?("<") && url_part.end_with?(">")

    url = url_part[1..-2]
    rel = params.find { |p| p.start_with?("rel=") }
    next unless rel

    rel_value = rel.sub(/\Arel="?/, "").sub(/"?\z/, "")
    acc[rel_value] = url
  end
end

.total_count(headers) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/wiq/pagination.rb', line 33

def total_count(headers)
  # Header is literally `TotalCount` (case-insensitive via Faraday).
  v = headers["TotalCount"] || headers["totalcount"] || headers["Totalcount"]
  v && Integer(v)
rescue ArgumentError
  nil
end