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: {})

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

Returns:

  • (ActiveRecord::Relation, Array)


18
19
20
21
# File 'lib/jsonapi/utils/support/pagination.rb', line 18

def apply_pagination(records, options = {})
  return records unless apply_pagination?(options)
  records.is_a?(Array) ? records[paginate_with(:range)] : paginate_with(:paginator).apply(records, nil)
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}



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

def pagination_params(records, options)
  return {} unless JSONAPI.configuration.top_level_links_include_pagination
  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



53
54
55
# File 'lib/jsonapi/utils/support/pagination.rb', line 53

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