module CursorPagination::ActiveRecord::RelationMethods

Attributes

cursor_key[RW]

Public Instance Methods

after(options) click to toggle source
# File lib/cursor-paginate/active_record.rb, line 26
def after(options)
  options = HashWithIndifferentAccess.new(options)

  rel = if ::ActiveRecord::Relation === self
          self
        else
          all
        end

  rel.cursor_key = rel.model.columns.map(&:name).find { |column| options.key? column }
  raise CursorPagination::InvalidColumnGiven unless rel.cursor_key

  cursor = options[rel.cursor_key]

  rel.where(cursor ? arel_table[rel.cursor_key].gteq(cursor) : nil).reorder(arel_table[rel.cursor_key].asc)
end
before(options) click to toggle source
# File lib/cursor-paginate/active_record.rb, line 9
def before(options)
  options = HashWithIndifferentAccess.new(options)

  rel = if ::ActiveRecord::Relation === self
          self
        else
          all
        end

  rel.cursor_key = rel.model.columns.map(&:name).find { |column| options.key? column }
  raise CursorPagination::InvalidColumnGiven unless rel.cursor_key

  cursor = options[rel.cursor_key]

  rel.where(cursor ? arel_table[rel.cursor_key].lteq(cursor) : nil).reorder(arel_table[rel.cursor_key].desc)
end
has_next?() click to toggle source
# File lib/cursor-paginate/active_record.rb, line 43
def has_next?
  set_next if @has_next.nil?
  @has_next
end
load() click to toggle source

Override ActiveRecord::Relation#load

Calls superclass method
# File lib/cursor-paginate/active_record.rb, line 54
def load
  return super unless cursor_key

  rel = super
  rel.set_next
  rel
end
next_cursor() click to toggle source
# File lib/cursor-paginate/active_record.rb, line 48
def next_cursor
  set_next if @has_next.nil?
  @next_cursor
end

Protected Instance Methods

set_next() click to toggle source
# File lib/cursor-paginate/active_record.rb, line 64
def set_next
  rel = self
  raise CursorPagination::LimitNotSet if rel.limit_value.nil?

  excess = rel.dup.tap { |r| r.limit_value = r.limit_value + 1 }

  if excess.size > rel.size
    @has_next = true
    @next_cursor = excess.last[cursor_key]
  else
    @has_next = false
    @next_cursor = nil
  end
end