Created
July 27, 2011 10:38
-
-
Save rvanlieshout/1109118 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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