Skip to content

Instantly share code, notes, and snippets.

@epochwolf
Created July 26, 2010 14:47
Show Gist options
  • Save epochwolf/490635 to your computer and use it in GitHub Desktop.
Save epochwolf/490635 to your computer and use it in GitHub Desktop.
# First rule of pasting code, add comments to explain logic and data structres
# when it's non-obvious in the code. (Pretty much always)
class MongoMapperDocument
# Searches for documents
#
# Structure for `criteria`
# [
# {
# "field" => "comments_count"
# "operator" => "gte" #or nil
# "value" => "4"
# },
# ]
def self.search(criteria, options={})
valid_operators = %w(gt lt gte lte ne in nin mod all exists asc desc) #valid for plucky in ruby 1.9, see plucky source
#protect against invalid operators being called.
criteria.each do |h|
unless h["operator"].nil? || valid_operators.include?(h["operator"])
h["operator"] = nil
end
end
new_query = where(options) #allow limits and stuff to be set using `options`
criteria.each do |h|
#expanded code to make it easier to follow
field = h["field"].to_sym
operator = h["operator"].nil? nil : h["operator"].to_sym
value = h["value"]
field = field.send(operator) if operator
#building query, not executed yet.
new_query = new_query.where(field => value)
end
return new_query # we return the query, the database has not been hit at this point.
# The object returns acts like an array. It will load data from the database when it's needed to populate the array.
end
end
@epochwolf
Copy link
Author

Beware of bugs in the code. I have neither proofed or tested it. ;)

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