Skip to content

Instantly share code, notes, and snippets.

@gusridd
Forked from justinweiss/filterable.rb
Created April 11, 2016 03:24
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 gusridd/9e80f763bae56a425aff310eeef0ae0f to your computer and use it in GitHub Desktop.
Save gusridd/9e80f763bae56a425aff310eeef0ae0f 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 the same name as the keys in <tt>filtering_params</tt>
# with their associated values. 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)
results = self.where(nil) # create an anonymous scope
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results.distinct
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment