Skip to content

Instantly share code, notes, and snippets.

@Pomeha
Created April 7, 2020 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Pomeha/91b41e04273bd7db3f0caa3d450b5995 to your computer and use it in GitHub Desktop.
Save Pomeha/91b41e04273bd7db3f0caa3d450b5995 to your computer and use it in GitHub Desktop.
Infinite scroll example
# frozen_string_literal: true
class Paginate
def call(
scope,
direction: 'asc',
field: nil,
last_id: nil,
field_value: nil,
limit: nil
)
scope = order_scope(scope, field, direction)
scope = filter(scope, field, direction, field_value) if field && field_value
scope = filter(scope, 'id', direction, last_id, '') if last_id
scope = scope.limit(limit) if limit
scope
end
private
COMPARERS = { asc: '>', desc: '<' }.freeze
def order_scope(scope, field, direction)
order_clause = field ? { field => direction } : {}
scope.order(order_clause.merge(id: direction))
end
def filter(scope, field, direction, field_value, eq = '=')
comparer = COMPARERS[direction.to_sym] + eq
field = field.include?('.') ? field : (scope.table_name + ".#{field}")
scope.where("#{field} #{comparer} ?", field_value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment