Skip to content

Instantly share code, notes, and snippets.

@rvanlieshout
Created July 27, 2011 10:38
Show Gist options
  • Save rvanlieshout/1109118 to your computer and use it in GitHub Desktop.
Save rvanlieshout/1109118 to your computer and use it in GitHub Desktop.
# Include this module in your ActiveRecord model to gain a filter scope
# Filter applies the supplied query to given attributes (or all attributes if none are given)
#
# example:
#
# User.filter('Bob', [:first_name, :last_name])
#
# returns all users with 'bob' in their first or last name
module Lico
module FilterScope
def self.included(base)
base.class_eval do
scope :filter, lambda { |query, attributes|
return if query.blank?
collection = self
attributes = collection.new.attributes unless attributes
query.split(/\s/).each do |phrase|
conditions = [""]
attributes.each do |attribute|
conditions[0] += attribute.to_s + " LIKE ? OR "
conditions.push "%#{phrase}%"
end
conditions[0] = conditions[0].sub(/ OR $/,"")
collection = collection.where(conditions)
end
collection
}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment