Skip to content

Commit

Permalink
Enable chain-able search for criteria
Browse files Browse the repository at this point in the history
  • Loading branch information
da-z committed Apr 9, 2011
1 parent 47af817 commit ee59ce4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/mongoid_search/mongoid_search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,18 @@ def search(query, options={})
search_without_relevance(query, options)
end
end

# Mongoid 2.0.0 introduces Criteria.seach so we need to provide
# alternate method
alias csearch search

def search_without_relevance(query, options={})
return self.all if query.blank? && allow_empty_search
self.send("#{(options[:match]||self.match).to_s}_in", :_keywords => Util.keywords(query, stem_keywords, ignore_list).map { |q| /#{q}/ })
return criteria.all if query.blank? && allow_empty_search
criteria.send("#{(options[:match]||self.match).to_s}_in", :_keywords => Util.keywords(query, stem_keywords, ignore_list).map { |q| /#{q}/ })
end

def search_relevant(query, options={})
return self.all if query.blank? && allow_empty_search
return criteria.all if query.blank? && allow_empty_search

keywords = Util.keywords(query, stem_keywords, ignore_list)

Expand Down Expand Up @@ -64,7 +68,7 @@ def search_relevant(query, options={})
{:_keywords => kw}
end

criteria = self.any_of(*kw_conditions)
criteria = criteria.any_of(*kw_conditions)

query = criteria.selector

Expand Down
17 changes: 17 additions & 0 deletions spec/mongoid_search_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,21 @@
it "should search for embedded documents" do
Product.search("craddle").size.should == 1
end

it 'should work in a chainable fashion' do
c = Category.create(:name => 'cat')
@product.category = c
c.products << @product
@product.save
c.save
c.reload
@product.reload
c.products.should_not be_empty
@product.category.should eq c
c.products.where(:brand => 'Apple').csearch('apple').size.should == 1
c.products.csearch('craddle').size.should == 1
Product.allow_empty_search = true
c.products.csearch("").size.should == 1
end

end

0 comments on commit ee59ce4

Please sign in to comment.