Class: ArPagination::CursorPagination::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/ar_pagination/cursor_pagination/query.rb

Instance Method Summary collapse

Constructor Details

#initialize(scope, cursor_key = :id) ⇒ Query

Returns a new instance of Query.

Parameters:

  • scope (ActiveRecord::Relation)

    inwhich to find current page

  • [Symbol] (Hash)

    a customizable set of options



8
9
10
11
# File 'lib/ar_pagination/cursor_pagination/query.rb', line 8

def initialize(scope, cursor_key = :id)
  @scope = scope
  @cursor_key = cursor_key
end

Instance Method Details

#fetch(cursor: -1,, count: 50, sort: "") ⇒ Pagination::Page

Fetch record for given cursor

Parameters:

  • [Fixnum] (Hash)

    a customizable set of options

Returns:

  • (Pagination::Page)

    dataset including next&prev cursors

See Also:



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ar_pagination/cursor_pagination/query.rb', line 19

def fetch(cursor: -1, count: 50, sort: "")

  # 1. sort if required
  @scope = ArPagination::Helpers::Sort.new(@scope).sort(sort)

  # 2. only need array of cursor keys from scope
  scope_keyed = @scope.pluck(@cursor_key)

  cursor = 0 if cursor == -1

  # check direction
  window =
    if cursor.to_s.first == "-"
      cursor = cursor.is_a?(Integer) ? cursor.abs : cursor.to_s[1..-1]
      backward(@scope, scope_keyed.index(cursor), count)
    else
      forward(@scope, scope_keyed.index(cursor), count)
    end

  Page.new(window, cursor, @cursor_key, count: count)
end