Permalink
Browse files

Merge branch 'search-refactor'

  • Loading branch information...
andrewtimberlake committed Jul 29, 2011
2 parents 9fd08e9 + 9a076fc commit b18171e96460006bf8f1ef0ff18c994904231139
Showing with 23 additions and 7 deletions.
  1. +12 −7 lib/tire/model/search.rb
  2. +11 −0 test/unit/model_search_test.rb
View
@@ -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
@@ -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

0 comments on commit b18171e

Please sign in to comment.