Class: Uchi::Pagy::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/uchi/pagy/classes/request.rb

Overview

Decouple the reuest from the env, allowing non-rack apps to use pagy by passing a hash. Resolve :page and :limit, supporting the :jsonapi option. Support for URL composition.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(request, options = {}) ⇒ Request

Returns a new instance of Request.



8
9
10
11
12
13
14
15
16
17
# File 'lib/uchi/pagy/classes/request.rb', line 8

def initialize(request, options = {})
  @base_url, @path, @query, @cookie =
    if request.is_a?(Hash)
      request.values_at(:base_url, :path, :query, :cookie)
    else
      [request.base_url, request.path, request.GET, request.cookies['pagy']]
    end
  @jsonapi = @query['page'] && options[:jsonapi]
  raise JsonapiReservedParamError, @query['page'] if @jsonapi && !@query['page'].respond_to?(:fetch)
end

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



19
20
21
# File 'lib/uchi/pagy/classes/request.rb', line 19

def base_url
  @base_url
end

Returns the value of attribute cookie.



19
20
21
# File 'lib/uchi/pagy/classes/request.rb', line 19

def cookie
  @cookie
end

#pathObject (readonly)

Returns the value of attribute path.



19
20
21
# File 'lib/uchi/pagy/classes/request.rb', line 19

def path
  @path
end

#queryObject (readonly)

Returns the value of attribute query.



19
20
21
# File 'lib/uchi/pagy/classes/request.rb', line 19

def query
  @query
end

Instance Method Details

#resolve_limit(options) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/uchi/pagy/classes/request.rb', line 28

def resolve_limit(options)
  limit_key = options[:limit_key] || DEFAULT[:limit_key]
  return options[:limit] || DEFAULT[:limit] \
        unless options[:client_max_limit] &&
                (requested_limit = @jsonapi ? @query['page'][limit_key] : @query[limit_key])

  [requested_limit.to_i, options[:client_max_limit]].min
end

#resolve_page(options, force_integer: true) ⇒ Object



21
22
23
24
25
26
# File 'lib/uchi/pagy/classes/request.rb', line 21

def resolve_page(options, force_integer: true)
  page_key = options[:page_key] || DEFAULT[:page_key]
  page     = @jsonapi ? @query['page'][page_key] : @query[page_key]
  page     = nil if page == ''   # fix for app-generated queries like ?page=
  force_integer ? (page || 1).to_i : page
end