Created
April 7, 2020 10:27
-
-
Save Pomeha/91b41e04273bd7db3f0caa3d450b5995 to your computer and use it in GitHub Desktop.
Infinite scroll example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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