Skip to content

Instantly share code, notes, and snippets.

@phurni
Forked from justinweiss/filterable.rb
Last active February 21, 2020 15:45
Show Gist options
  • Save phurni/79540f88b60f3457272e2d8aac196b5c to your computer and use it in GitHub Desktop.
Save phurni/79540f88b60f3457272e2d8aac196b5c to your computer and use it in GitHub Desktop.
Filterable
# Call scopes directly from your URL params:
#
# @products = Product.filter(params.slice(:status, :location, :starts_with))
module Filterable
extend ActiveSupport::Concern
module ClassMethods
# Call the class methods with names based on the keys in <tt>filtering_params</tt>
# with their associated values. For example, "{ status: 'delayed' }" would call
# `filter_by_status('delayed')`. Most useful for calling named scopes from
# URL params. Make sure you don't pass stuff directly from the web without
# whitelisting only the params you care about first!
def filter(filtering_params)
filtering_params.reject {|key, value| value.blank? }.reduce(self.where(nil)) {|scope, (key, value)| scope.public_send("filter_by_#{key}", value) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment