Module: JSONAPI::Utils::Support::Pagination

Included in:
Response::Support
Defined in:
lib/jsonapi/utils/support/pagination.rb

Constant Summary collapse

RecordCountError =
Class.new(ArgumentError)

Instance Method Summary collapse

Instance Method Details

#apply_pagination(records, options = {}) ⇒ ActiveRecord::Relation, Array

Apply proper pagination to the records.

Parameters:

  • records (ActiveRecord::Relation, Array)

    collection of records e.g.: User.all or [{ id: 1, name: ‘Tiago’ }, { id: 2, name: ‘Doug’ }]

  • options (Hash) (defaults to: {})

    JSONAPI::Utils’ options e.g.: { resource: V2::UserResource, count: 100 }

Returns:

  • (ActiveRecord::Relation, Array)


36
37
38
39
40
41
# File 'lib/jsonapi/utils/support/pagination.rb', line 36

def apply_pagination(records, options = {})
  if !apply_pagination?(options) then records
  elsif records.is_a?(Array)     then records[paginate_with(:range)]
  else paginate_with(:paginator).apply(records, nil)
  end
end

#include_page_count?Boolean

Check whether pagination’s page count should be included on the “meta” key.

Returns:

  • (Boolean)


21
22
23
# File 'lib/jsonapi/utils/support/pagination.rb', line 21

def include_page_count?
  JSONAPI.configuration.top_level_meta_include_page_count
end

#include_pagination_links?Boolean

Check whether pagination links should be included.

Returns:

  • (Boolean)


11
12
13
14
# File 'lib/jsonapi/utils/support/pagination.rb', line 11

def include_pagination_links?
  JSONAPI.configuration.default_paginator != :none &&
    JSONAPI.configuration.top_level_links_include_pagination
end

#pagination_params(records, options) ⇒ Hash

Mount pagination params for JSONAPI::ResourcesOperationResult. It can also be used anywhere else as a helper method.

Parameters:

  • records (ActiveRecord::Relation, Array)

    collection of records e.g.: User.all or [{ id: 1, name: ‘Tiago’ }, { id: 2, name: ‘Doug’ }]

  • options (Hash)

    JU’s options e.g.: { resource: V2::UserResource, count: 100 }

Returns:

  • (Hash)

    e.g.: “size”=>2, “next”=>“size”=>2, “last”=>“size”=>2}



57
58
59
60
# File 'lib/jsonapi/utils/support/pagination.rb', line 57

def pagination_params(records, options)
  return {} unless include_pagination_links?
  paginator.links_page_params(record_count: record_count_for(records, options))
end

#record_count_for(records, options) ⇒ Integer

Apply memoization to the record count result avoiding duplicate counts.

Parameters:

  • records (ActiveRecord::Relation, Array)

    collection of records e.g.: User.all or [{ id: 1, name: ‘Tiago’ }, { id: 2, name: ‘Doug’ }]

  • options (Hash)

    JU’s options e.g.: { resource: V2::UserResource, count: 100 }

Returns:

  • (Integer)

    e.g.: 42



74
75
76
# File 'lib/jsonapi/utils/support/pagination.rb', line 74

def record_count_for(records, options)
  @record_count ||= count_records(records, options)
end