Skip to content

Instantly share code, notes, and snippets.

@syafiqfaiz
Created June 14, 2019 03:05
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 syafiqfaiz/f1c0a4338a2147241baba7a45157d3ef to your computer and use it in GitHub Desktop.
Save syafiqfaiz/f1c0a4338a2147241baba7a45157d3ef to your computer and use it in GitHub Desktop.
A module to make a clean and simple filtering
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil)
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
.
.
.
class User < ApplicationRecord
include Filterable
scope :email_q, -> (email) { where("LOWER(email) like ?", "%#{email.downcase}%")}
scope :name_q, -> (name) { where("LOWER(name) like ?", "%#{name.downcase}%")}
end
.
.
.
def index
@users = User.filter(filtering_params)
end
def filtering_params
params.slice(:email_q, :name_q)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment