class GraphQL::Pagination::ArrayConnection

Public Instance Methods

cursor_for(item) click to toggle source
# File lib/graphql/pagination/array_connection.rb, line 22
def cursor_for(item)
  idx = items.find_index(item) + 1
  encode(idx.to_s)
end
has_next_page() click to toggle source
# File lib/graphql/pagination/array_connection.rb, line 17
def has_next_page
  load_nodes
  @has_next_page
end
has_previous_page() click to toggle source
# File lib/graphql/pagination/array_connection.rb, line 12
def has_previous_page
  load_nodes
  @has_previous_page
end
nodes() click to toggle source
# File lib/graphql/pagination/array_connection.rb, line 7
def nodes
  load_nodes
  @nodes
end

Private Instance Methods

index_from_cursor(cursor) click to toggle source
# File lib/graphql/pagination/array_connection.rb, line 29
def index_from_cursor(cursor)
  decode(cursor).to_i
end
load_nodes() click to toggle source

Populate all the pagination info once, It doesn't do anything on subsequent calls.

# File lib/graphql/pagination/array_connection.rb, line 35
def load_nodes
  @nodes ||= begin
    sliced_nodes = if before && after
      items[index_from_cursor(after)..index_from_cursor(before)-1] || []
    elsif before
      items[0..index_from_cursor(before)-2] || []
    elsif after
      items[index_from_cursor(after)..-1] || []
    else
      items
    end

    @has_previous_page = if last
      # There are items preceding the ones in this result
      sliced_nodes.count > last
    elsif after
      # We've paginated into the Array a bit, there are some behind us
      index_from_cursor(after) > 0
    else
      false
    end

    @has_next_page = if first
      # There are more items after these items
      sliced_nodes.count > first
    elsif before
      # The original array is longer than the `before` index
      index_from_cursor(before) < items.length + 1
    else
      false
    end

    limited_nodes = sliced_nodes

    limited_nodes = limited_nodes.first(first) if first
    limited_nodes = limited_nodes.last(last) if last

    limited_nodes
  end
end