Class: JsonapiCompliable::Scoping::Paginate

Inherits:
Base
  • Object
show all
Defined in:
lib/jsonapi_compliable/scoping/paginate.rb

Overview

Apply pagination logic to the scope

If the user requests a page size greater than MAX_PAGE_SIZE, a JsonapiCompliable::Errors::UnsupportedPageSize error will be raised.

Notably, this will not fire when the `default: false` option is passed. This is the case for sideloads - if the user requests “give me the post and its comments”, we shouldn't implicitly limit those comments to 20. BUT if the user requests, “give me the post and 3 of its comments”, we should honor that pagination.

This can be confusing because there are also 'default' and 'customized' pagination procs. The default comes 'for free'. Customized pagination looks like

class PostResource < ApplicationResource
  paginate do |scope, current_page, per_page|
    # ... the custom logic ...
  end
end

We should use the default unless the user has customized.

See Also:

Constant Summary

MAX_PAGE_SIZE =
1_000

Instance Attribute Summary

Attributes inherited from Base

#query_hash, #resource

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from JsonapiCompliable::Scoping::Base

Instance Method Details

#applyObject

Apply the pagination logic. Raise error if over the max page size.

Returns:

  • the scope object we are chaining/modifying



30
31
32
33
34
35
36
37
# File 'lib/jsonapi_compliable/scoping/paginate.rb', line 30

def apply
  if size > MAX_PAGE_SIZE
    raise JsonapiCompliable::Errors::UnsupportedPageSize
      .new(size, MAX_PAGE_SIZE)
  else
    super
  end
end

#apply?Boolean

We want to apply this logic unless we've explicitly received the default: false option. In that case, only apply if pagination was explicitly specified in the request.

Returns:

  • (Boolean)

    should we apply this logic?



44
45
46
47
48
49
50
# File 'lib/jsonapi_compliable/scoping/paginate.rb', line 44

def apply?
  if @opts[:default] == false
    not [page_param[:size], page_param[:number]].all?(&:nil?)
  else
    true
  end
end

#apply_custom_scopeObject

Apply the custom pagination proc



63
64
65
# File 'lib/jsonapi_compliable/scoping/paginate.rb', line 63

def apply_custom_scope
  custom_scope.call(@scope, number, size, resource.context)
end

#apply_standard_scopeObject

Apply default pagination proc via the Resource adapter



58
59
60
# File 'lib/jsonapi_compliable/scoping/paginate.rb', line 58

def apply_standard_scope
  resource.adapter.paginate(@scope, number, size)
end

#custom_scopeProc, Nil

Returns the custom pagination proc

Returns:

  • (Proc, Nil)

    the custom pagination proc



53
54
55
# File 'lib/jsonapi_compliable/scoping/paginate.rb', line 53

def custom_scope
  resource.pagination
end