Last active
November 4, 2016 19:19
-
-
Save eiwi1101/0f0ebb0a739c1206b9dba316fba947c6 to your computer and use it in GitHub Desktop.
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
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