Skip to content

Commit

Permalink
Merge branch 'search-refactor'
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtimberlake committed Jul 29, 2011
2 parents 9fd08e9 + 9a076fc commit b18171e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
19 changes: 12 additions & 7 deletions lib/tire/model/search.rb
Expand Up @@ -32,30 +32,35 @@ def to_hash

module ClassMethods

def search(query=nil, options={}, &block)
# Usage:
#
# search('query', [options])
# search([options]) do <block> end
def search(*args, &block)
query = args.size >= 1 ? args[0] : nil
options = args.size > 0 ? (args.last.respond_to?(:keys) ? args.last : {}) : {}

old_wrapper = Tire::Configuration.wrapper
Tire::Configuration.wrapper self

sort = Array( options[:order] || options[:sort] )
options = {:type => document_type}.update(options)

s = Tire::Search::Search.new(elasticsearch_index.name, options)
s.size( options[:per_page].to_i ) if options[:per_page]
s.from( options[:page].to_i <= 1 ? 0 : (options[:per_page].to_i * (options[:page].to_i-1)) ) if options[:page] && options[:per_page]
unless block_given?
s = Tire::Search::Search.new(elasticsearch_index.name, options)
s.query { string query }
s.sort do
sort.each do |t|
field_name, direction = t.split(' ')
by field_name, direction
end
end unless sort.empty?
s.size( options[:per_page].to_i ) if options[:per_page]
s.from( options[:page].to_i <= 1 ? 0 : (options[:per_page].to_i * (options[:page].to_i-1)) ) if options[:page] && options[:per_page]
s.perform.results
else
s = Tire::Search::Search.new(elasticsearch_index.name, options)
block.arity < 1 ? s.instance_eval(&block) : block.call(s)
s.perform.results
end
s.perform.results
ensure
Tire::Configuration.wrapper old_wrapper
end
Expand Down
11 changes: 11 additions & 0 deletions test/unit/model_search_test.rb
Expand Up @@ -189,6 +189,17 @@ class SearchTest < Test::Unit::TestCase
ActiveModelArticle.search @q, :per_page => 10, :page => 3
end

should "allow to specify page even if using a block" do
Tire::Search::Search.any_instance.expects(:size).with(10)
Tire::Search::Search.any_instance.expects(:from).with(20)

ActiveModelArticle.search :per_page => 10, :page => 3 do
query do
string 'foo AND bar' #@q is not visible here
end
end
end

end

should "not set callback when hooks are missing" do
Expand Down

0 comments on commit b18171e

Please sign in to comment.