Skip to content

Instantly share code, notes, and snippets.

@noahhendrix
Last active September 4, 2015 20:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save noahhendrix/9119825 to your computer and use it in GitHub Desktop.
Save noahhendrix/9119825 to your computer and use it in GitHub Desktop.
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
filtering_params.reduce(self) do |relation, (scope_name, value)|
relation.public_send(scope_name, value) if value.present?
end
end
end
end
@adammiribyan
Copy link

Hi Noah, what is the reason the Enumerable#reduce returns nil if the hash key and value are passed like this |relation, scope_name, value|?

@adammiribyan
Copy link

Ok, I found the answer here. Destructuring in Ruby is a quite interesting topic I've somehow missed out.

@monfresh
Copy link

This will return nil if one or more of the parameters are passed with a blank value, which means you won't be able to chain any methods after .filter in the controller, such as .page(params[:page]) if you were using a pagination gem like Kaminari, for example. The filter method should always be returning a chainable relation, in this case via .all if none of the filters are set.

@monfresh
Copy link

Here's what it should look like:

filtering_params.reduce(self) do |relation, (scope_name, value)|
  value.present? ? relation.public_send(scope_name, value) : relation.all
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment