Skip to content

Instantly share code, notes, and snippets.

@eiwi1101
Last active November 4, 2016 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eiwi1101/0f0ebb0a739c1206b9dba316fba947c6 to your computer and use it in GitHub Desktop.
Save eiwi1101/0f0ebb0a739c1206b9dba316fba947c6 to your computer and use it in GitHub Desktop.
module CollectionHelper
#...
# This does a shitload of magic. It handles sort, order, filter, page and search.
#
def self.filter_scope(scope, params = {})
unpermitted_params = []
params = params.with_indifferent_access
params[:sort] ||= 'id'
params[:order] ||= 'asc'
params.keys.each do |key|
relation, column = key.to_s.split('.')
value = params[key].dup
negate = value[0] == '!'
value.slice!(0) if negate
value = [nil, ''] if value.blank? || value == '!'
if column.nil?
column = relation
relation = scope.table_name
end
table = relation.pluralize
if scope.connection.table_exists?(table) && scope.connection.column_exists?(table, column)
if table != scope.table_name
if scope.reflect_on_association(relation)
scope = scope.joins(relation.to_sym)
else
unpermitted_params << key
end
end
if negate
scope = scope.where.not("#{table}.#{column}" => value)
else
scope = scope.where("#{table}.#{column}" => value)
end
end
end
if params.include?(:q) or params.include?(:sort)
sort = params[:sort] ? "#{params[:sort].try(:downcase)} #{params[:order].try(:downcase)}".strip : ''
if scope.respond_to?(:search_for) && params[:q]
scope = scope.search_for(params[:q])
else
unpermitted_params << 'q' if params[:q]
end
scope = scope.order(sort)
end
unless params[:page] == 'all' || !scope.respond_to?(:page)
scope = scope.page(params[:page] || 1)
end
raise ActionController::UnpermittedParameters.new(unpermitted_params) if unpermitted_params.any?
scope
rescue ScopedSearch::QueryNotSupported => e
raise ActionController::RoutingError.new(e.message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment