Skip to content

Instantly share code, notes, and snippets.

@abriening
Created August 12, 2010 19:34
Show Gist options
  • Save abriening/521569 to your computer and use it in GitHub Desktop.
Save abriening/521569 to your computer and use it in GitHub Desktop.
named_scope :conditions, lambda { |args| {:conditions => args} }
named_scope :filter, lambda{ |options|
options ||= {}
options.stringify_keys!
scope = scoped(Hash.new)
unless options['active'].blank?
scope = scope.conditions :active => options['active']
end
where = []
values = []
%w[name email login].each do |attr|
unless options[attr].blank?
options[attr].split(' ').each do |value|
# the regexp match is probably faster
# but will probably only work with mysql
# where << "#{attr} REGEXP ?"
# values << "[[:<:]]#{value}"
#
# Same functionally as the regexp match
# find strings that start with value
# or a word that starts with value
where << "#{attr} LIKE ?"
values << "#{value}%"
where << "#{attr} LIKE ?"
values << "% #{value}%"
end
end
end
scope = scope.conditions [where.join(' OR '), *values] unless where.empty?
scope.scope :find
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment