Skip to content

Instantly share code, notes, and snippets.

@bkeepers
Created March 12, 2010 17:03
Show Gist options
  • Save bkeepers/330527 to your computer and use it in GitHub Desktop.
Save bkeepers/330527 to your computer and use it in GitHub Desktop.
class Hash
def rmerge!(other_hash)
merge!(other_hash) do |key, oldval, newval|
oldval.class == self.class ? oldval.rmerge!(newval) : newval
end
end
def rmerge(other_hash)
r = {}
merge(other_hash) do |key, oldval, newval|
r[key] = oldval.class == self.class ? oldval.rmerge(newval) : newval
end
end
end
class Object
def to_mm_criteria(value)
SymbolOperator.new(self, 'eq').to_mm_criteria(value)
end
end
module MongoMapper
class Query
def initialize
@criteria = {}
end
def where(criteria)
criteria.each do |key, value|
@criteria.rmerge!(key.to_mm_criteria(value))
end
self
end
def criteria
@criteria
end
end
end
require 'test_helper'
require 'models'
class QueryTest < Test::Unit::TestCase
include MongoMapper
context "where" do
should "generate criteria" do
Query.new.where(:foo => 'bar').criteria.should == {:foo => {'$eq' => 'bar'}}
end
should "merge criteria" do
Query.new.where(:foo => 'bar').where(:hello => 'world').criteria.should == {
:foo => {'$eq' => 'bar'}, :hello => {'$eq' => 'world'}
}
end
should "merge criteria on same attribute" do
Query.new.where(:foo => 'bar').where(:foo.ne => 'baz').criteria.should == {
:foo => {'$eq' => 'bar', '$ne' => 'baz'}
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment