Commit 7a24684bb470abd5ceca7a40b21d28584b910a4c

Authored by Andrew Kane
1 parent 53e7953f

Style updates

1 -source 'https://rubygems.org' 1 +source "https://rubygems.org"
2 2
3 # Specify your gem's dependencies in searchkick.gemspec 3 # Specify your gem's dependencies in searchkick.gemspec
4 gemspec 4 gemspec
1 require "bundler/gem_tasks" 1 require "bundler/gem_tasks"
2 require "rake/testtask" 2 require "rake/testtask"
3 3
4 -task :default => :test 4 +task default: :test
5 Rake::TestTask.new do |t| 5 Rake::TestTask.new do |t|
6 t.libs << "test" 6 t.libs << "test"
7 t.pattern = "test/**/*_test.rb" 7 t.pattern = "test/**/*_test.rb"
lib/searchkick.rb
@@ -44,8 +44,8 @@ module Searchkick @@ -44,8 +44,8 @@ module Searchkick
44 ) 44 )
45 end 45 end
46 46
47 - def self.client=(client)  
48 - @client = client 47 + class << self
  48 + attr_writer :client
49 end 49 end
50 50
51 def self.server_version 51 def self.server_version
lib/searchkick/index.rb
@@ -34,7 +34,7 @@ module Searchkick @@ -34,7 +34,7 @@ module Searchkick
34 rescue Elasticsearch::Transport::Transport::Errors::NotFound 34 rescue Elasticsearch::Transport::Transport::Errors::NotFound
35 [] 35 []
36 end 36 end
37 - actions = old_indices.map{|old_name| {remove: {index: old_name, alias: name}} } + [{add: {index: new_name, alias: name}}] 37 + actions = old_indices.map { |old_name| {remove: {index: old_name, alias: name}} } + [{add: {index: new_name, alias: name}}]
38 client.indices.update_aliases body: {actions: actions} 38 client.indices.update_aliases body: {actions: actions}
39 end 39 end
40 40
@@ -58,11 +58,11 @@ module Searchkick @@ -58,11 +58,11 @@ module Searchkick
58 end 58 end
59 59
60 def import(records) 60 def import(records)
61 - records.group_by{|r| document_type(r) }.each do |type, batch| 61 + records.group_by { |r| document_type(r) }.each do |type, batch|
62 client.bulk( 62 client.bulk(
63 index: name, 63 index: name,
64 type: type, 64 type: type,
65 - body: batch.map{|r| {index: {_id: search_id(r), data: search_data(r)}} } 65 + body: batch.map { |r| {index: {_id: search_id(r), data: search_data(r)}} }
66 ) 66 )
67 end 67 end
68 end 68 end
@@ -89,7 +89,7 @@ module Searchkick @@ -89,7 +89,7 @@ module Searchkick
89 89
90 def reindex_record_async(record) 90 def reindex_record_async(record)
91 if defined?(Searchkick::ReindexV2Job) 91 if defined?(Searchkick::ReindexV2Job)
92 - Searchkick::ReindexV2Job.perform_later(record.class.name, record.id.to_s) 92 + Searchkick::ReindexV2Job.perform_later(record.class.name, record.id.to_s)
93 else 93 else
94 Delayed::Job.enqueue Searchkick::ReindexJob.new(record.class.name, record.id.to_s) 94 Delayed::Job.enqueue Searchkick::ReindexJob.new(record.class.name, record.id.to_s)
95 end 95 end
@@ -97,7 +97,7 @@ module Searchkick @@ -97,7 +97,7 @@ module Searchkick
97 97
98 def similar_record(record, options = {}) 98 def similar_record(record, options = {})
99 like_text = retrieve(record).to_hash 99 like_text = retrieve(record).to_hash
100 - .keep_if{|k,v| !options[:fields] || options[:fields].map(&:to_s).include?(k) } 100 + .keep_if { |k, v| !options[:fields] || options[:fields].map(&:to_s).include?(k) }
101 .values.compact.join(" ") 101 .values.compact.join(" ")
102 102
103 # TODO deep merge method 103 # TODO deep merge method
@@ -136,7 +136,7 @@ module Searchkick @@ -136,7 +136,7 @@ module Searchkick
136 # remove old indices that start w/ index_name 136 # remove old indices that start w/ index_name
137 def clean_indices 137 def clean_indices
138 all_indices = client.indices.get_aliases 138 all_indices = client.indices.get_aliases
139 - indices = all_indices.select{|k, v| (v.empty? || v["aliases"].empty?) && k =~ /\A#{Regexp.escape(name)}_\d{14,17}\z/ }.keys 139 + indices = all_indices.select { |k, v| (v.empty? || v["aliases"].empty?) && k =~ /\A#{Regexp.escape(name)}_\d{14,17}\z/ }.keys
140 indices.each do |index| 140 indices.each do |index|
141 Searchkick::Index.new(index).delete 141 Searchkick::Index.new(index).delete
142 end 142 end
@@ -180,7 +180,7 @@ module Searchkick @@ -180,7 +180,7 @@ module Searchkick
180 scope = scope.search_import if scope.respond_to?(:search_import) 180 scope = scope.search_import if scope.respond_to?(:search_import)
181 if scope.respond_to?(:find_in_batches) 181 if scope.respond_to?(:find_in_batches)
182 scope.find_in_batches batch_size: batch_size do |batch| 182 scope.find_in_batches batch_size: batch_size do |batch|
183 - import batch.select{|item| item.should_index? } 183 + import batch.select(&:should_index?)
184 end 184 end
185 else 185 else
186 # https://github.com/karmi/tire/blob/master/lib/tire/model/import.rb 186 # https://github.com/karmi/tire/blob/master/lib/tire/model/import.rb
@@ -333,7 +333,7 @@ module Searchkick @@ -333,7 +333,7 @@ module Searchkick
333 if synonyms.any? 333 if synonyms.any?
334 settings[:analysis][:filter][:searchkick_synonym] = { 334 settings[:analysis][:filter][:searchkick_synonym] = {
335 type: "synonym", 335 type: "synonym",
336 - synonyms: synonyms.select{|s| s.size > 1 }.map{|s| s.join(",") } 336 + synonyms: synonyms.select { |s| s.size > 1 }.map { |s| s.join(",") }
337 } 337 }
338 # choosing a place for the synonym filter when stemming is not easy 338 # choosing a place for the synonym filter when stemming is not easy
339 # https://groups.google.com/forum/#!topic/elasticsearch/p7qcQlgHdB8 339 # https://groups.google.com/forum/#!topic/elasticsearch/p7qcQlgHdB8
@@ -361,7 +361,7 @@ module Searchkick @@ -361,7 +361,7 @@ module Searchkick
361 361
362 if options[:special_characters] == false 362 if options[:special_characters] == false
363 settings[:analysis][:analyzer].each do |analyzer, analyzer_settings| 363 settings[:analysis][:analyzer].each do |analyzer, analyzer_settings|
364 - analyzer_settings[:filter].reject!{|f| f == "asciifolding" } 364 + analyzer_settings[:filter].reject! { |f| f == "asciifolding" }
365 end 365 end
366 end 366 end
367 367
@@ -380,7 +380,7 @@ module Searchkick @@ -380,7 +380,7 @@ module Searchkick
380 380
381 mapping_options = Hash[ 381 mapping_options = Hash[
382 [:autocomplete, :suggest, :text_start, :text_middle, :text_end, :word_start, :word_middle, :word_end, :highlight] 382 [:autocomplete, :suggest, :text_start, :text_middle, :text_end, :word_start, :word_middle, :word_end, :highlight]
383 - .map{|type| [type, (options[type] || []).map(&:to_s)] } 383 + .map { |type| [type, (options[type] || []).map(&:to_s)] }
384 ] 384 ]
385 385
386 mapping_options.values.flatten.uniq.each do |field| 386 mapping_options.values.flatten.uniq.each do |field|
@@ -457,7 +457,7 @@ module Searchkick @@ -457,7 +457,7 @@ module Searchkick
457 # other 457 # other
458 458
459 def tokens(text, options = {}) 459 def tokens(text, options = {})
460 - client.indices.analyze({text: text, index: name}.merge(options))["tokens"].map{|t| t["token"] } 460 + client.indices.analyze({text: text, index: name}.merge(options))["tokens"].map { |t| t["token"] }
461 end 461 end
462 462
463 def klass_document_type(klass) 463 def klass_document_type(klass)
@@ -488,24 +488,24 @@ module Searchkick @@ -488,24 +488,24 @@ module Searchkick
488 488
489 # stringify fields 489 # stringify fields
490 # remove _id since search_id is used instead 490 # remove _id since search_id is used instead
491 - source = source.inject({}){|memo,(k,v)| memo[k.to_s] = v; memo}.except("_id") 491 + source = source.inject({}) { |memo, (k, v)| memo[k.to_s] = v; memo }.except("_id")
492 492
493 # conversions 493 # conversions
494 conversions_field = options[:conversions] 494 conversions_field = options[:conversions]
495 if conversions_field && source[conversions_field] 495 if conversions_field && source[conversions_field]
496 - source[conversions_field] = source[conversions_field].map{|k, v| {query: k, count: v} } 496 + source[conversions_field] = source[conversions_field].map { |k, v| {query: k, count: v} }
497 end 497 end
498 498
499 # hack to prevent generator field doesn't exist error 499 # hack to prevent generator field doesn't exist error
500 (options[:suggest] || []).map(&:to_s).each do |field| 500 (options[:suggest] || []).map(&:to_s).each do |field|
501 - source[field] = nil if !source[field] 501 + source[field] = nil unless source[field]
502 end 502 end
503 503
504 # locations 504 # locations
505 (options[:locations] || []).map(&:to_s).each do |field| 505 (options[:locations] || []).map(&:to_s).each do |field|
506 if source[field] 506 if source[field]
507 if source[field].first.is_a?(Array) # array of arrays 507 if source[field].first.is_a?(Array) # array of arrays
508 - source[field] = source[field].map{|a| a.map(&:to_f).reverse } 508 + source[field] = source[field].map { |a| a.map(&:to_f).reverse }
509 else 509 else
510 source[field] = source[field].map(&:to_f).reverse 510 source[field] = source[field].map(&:to_f).reverse
511 end 511 end
lib/searchkick/logging.rb
@@ -77,7 +77,7 @@ module Searchkick @@ -77,7 +77,7 @@ module Searchkick
77 77
78 # no easy way to tell which host the client will use 78 # no easy way to tell which host the client will use
79 host = Searchkick.client.transport.hosts.first 79 host = Searchkick.client.transport.hosts.first
80 - debug " #{color(name, YELLOW, true)} curl #{host[:protocol]}://#{host[:host]}:#{host[:port]}/#{CGI.escape(index)}#{type ? "/#{type.map{|t| CGI.escape(t) }.join(",")}" : ""}/_search?pretty -d '#{payload[:query][:body].to_json}'" 80 + debug " #{color(name, YELLOW, true)} curl #{host[:protocol]}://#{host[:host]}:#{host[:port]}/#{CGI.escape(index)}#{type ? "/#{type.map { |t| CGI.escape(t) }.join(',')}" : ''}/_search?pretty -d '#{payload[:query][:body].to_json}'"
81 end 81 end
82 82
83 def request(event) 83 def request(event)
lib/searchkick/model.rb
@@ -11,14 +11,14 @@ module Searchkick @@ -11,14 +11,14 @@ module Searchkick
11 class_eval do 11 class_eval do
12 cattr_reader :searchkick_options, :searchkick_klass 12 cattr_reader :searchkick_options, :searchkick_klass
13 13
14 - callbacks = options.has_key?(:callbacks) ? options[:callbacks] : true 14 + callbacks = options.key?(:callbacks) ? options[:callbacks] : true
15 15
16 class_variable_set :@@searchkick_options, options.dup 16 class_variable_set :@@searchkick_options, options.dup
17 class_variable_set :@@searchkick_klass, self 17 class_variable_set :@@searchkick_klass, self
18 class_variable_set :@@searchkick_callbacks, callbacks 18 class_variable_set :@@searchkick_callbacks, callbacks
19 class_variable_set :@@searchkick_index, options[:index_name] || [options[:index_prefix], model_name.plural, Searchkick.env].compact.join("_") 19 class_variable_set :@@searchkick_index, options[:index_name] || [options[:index_prefix], model_name.plural, Searchkick.env].compact.join("_")
20 20
21 - define_singleton_method(Searchkick.search_method_name) do |term = nil, options={}, &block| 21 + define_singleton_method(Searchkick.search_method_name) do |term = nil, options = {}, &block|
22 searchkick_index.search_model(self, term, options, &block) 22 searchkick_index.search_model(self, term, options, &block)
23 end 23 end
24 extend Searchkick::Reindex # legacy for Searchjoy 24 extend Searchkick::Reindex # legacy for Searchjoy
@@ -68,10 +68,10 @@ module Searchkick @@ -68,10 +68,10 @@ module Searchkick
68 if callbacks 68 if callbacks
69 callback_name = callbacks == :async ? :reindex_async : :reindex 69 callback_name = callbacks == :async ? :reindex_async : :reindex
70 if respond_to?(:after_commit) 70 if respond_to?(:after_commit)
71 - after_commit callback_name, if: proc{ self.class.search_callbacks? } 71 + after_commit callback_name, if: proc { self.class.search_callbacks? }
72 else 72 else
73 - after_save callback_name, if: proc{ self.class.search_callbacks? }  
74 - after_destroy callback_name, if: proc{ self.class.search_callbacks? } 73 + after_save callback_name, if: proc { self.class.search_callbacks? }
  74 + after_destroy callback_name, if: proc { self.class.search_callbacks? }
75 end 75 end
76 end 76 end
77 77
lib/searchkick/query.rb
@@ -22,19 +22,19 @@ module Searchkick @@ -22,19 +22,19 @@ module Searchkick
22 fields = 22 fields =
23 if options[:fields] 23 if options[:fields]
24 if options[:autocomplete] 24 if options[:autocomplete]
25 - options[:fields].map{|f| "#{f}.autocomplete" } 25 + options[:fields].map { |f| "#{f}.autocomplete" }
26 else 26 else
27 options[:fields].map do |value| 27 options[:fields].map do |value|
28 k, v = value.is_a?(Hash) ? value.to_a.first : [value, :word] 28 k, v = value.is_a?(Hash) ? value.to_a.first : [value, :word]
29 k2, boost = k.to_s.split("^", 2) 29 k2, boost = k.to_s.split("^", 2)
30 - field = "#{k2}.#{v == :word ? "analyzed" : v}" 30 + field = "#{k2}.#{v == :word ? 'analyzed' : v}"
31 boost_fields[field] = boost.to_f if boost 31 boost_fields[field] = boost.to_f if boost
32 field 32 field
33 end 33 end
34 end 34 end
35 else 35 else
36 if options[:autocomplete] 36 if options[:autocomplete]
37 - (searchkick_options[:autocomplete] || []).map{|f| "#{f}.autocomplete" } 37 + (searchkick_options[:autocomplete] || []).map { |f| "#{f}.autocomplete" }
38 else 38 else
39 ["_all"] 39 ["_all"]
40 end 40 end
@@ -44,7 +44,7 @@ module Searchkick @@ -44,7 +44,7 @@ module Searchkick
44 44
45 # pagination 45 # pagination
46 page = [options[:page].to_i, 1].max 46 page = [options[:page].to_i, 1].max
47 - per_page = (options[:limit] || options[:per_page] || 100000).to_i 47 + per_page = (options[:limit] || options[:per_page] || 100_000).to_i
48 padding = [options[:padding].to_i, 0].max 48 padding = [options[:padding].to_i, 0].max
49 offset = options[:offset] || (page - 1) * per_page + padding 49 offset = options[:offset] || (page - 1) * per_page + padding
50 50
@@ -104,7 +104,7 @@ module Searchkick @@ -104,7 +104,7 @@ module Searchkick
104 shared_options.merge(boost: 10 * factor, analyzer: "searchkick_search"), 104 shared_options.merge(boost: 10 * factor, analyzer: "searchkick_search"),
105 shared_options.merge(boost: 10 * factor, analyzer: "searchkick_search2") 105 shared_options.merge(boost: 10 * factor, analyzer: "searchkick_search2")
106 ] 106 ]
107 - misspellings = options.has_key?(:misspellings) ? options[:misspellings] : options[:mispellings] # why not? 107 + misspellings = options.key?(:misspellings) ? options[:misspellings] : options[:mispellings] # why not?
108 if misspellings != false 108 if misspellings != false
109 edit_distance = (misspellings.is_a?(Hash) && (misspellings[:edit_distance] || misspellings[:distance])) || 1 109 edit_distance = (misspellings.is_a?(Hash) && (misspellings[:edit_distance] || misspellings[:distance])) || 1
110 qs.concat [ 110 qs.concat [
@@ -120,7 +120,7 @@ module Searchkick @@ -120,7 +120,7 @@ module Searchkick
120 qs << shared_options.merge(analyzer: analyzer) 120 qs << shared_options.merge(analyzer: analyzer)
121 end 121 end
122 122
123 - queries.concat(qs.map{|q| {match: {field => q}} }) 123 + queries.concat(qs.map { |q| {match: {field => q}} })
124 end 124 end
125 125
126 payload = { 126 payload = {
@@ -167,7 +167,7 @@ module Searchkick @@ -167,7 +167,7 @@ module Searchkick
167 167
168 boost_by = options[:boost_by] || {} 168 boost_by = options[:boost_by] || {}
169 if boost_by.is_a?(Array) 169 if boost_by.is_a?(Array)
170 - boost_by = Hash[ boost_by.map{|f| [f, {factor: 1}] } ] 170 + boost_by = Hash[boost_by.map { |f| [f, {factor: 1}] }]
171 end 171 end
172 if options[:boost] 172 if options[:boost]
173 boost_by[options[:boost]] = {factor: 1} 173 boost_by[options[:boost]] = {factor: 1}
@@ -218,7 +218,7 @@ module Searchkick @@ -218,7 +218,7 @@ module Searchkick
218 if !boost_by_distance[:field] || !boost_by_distance[:origin] 218 if !boost_by_distance[:field] || !boost_by_distance[:origin]
219 raise ArgumentError, "boost_by_distance requires :field and :origin" 219 raise ArgumentError, "boost_by_distance requires :field and :origin"
220 end 220 end
221 - function_params = boost_by_distance.select{|k,v| [:origin, :scale, :offset, :decay].include?(k) } 221 + function_params = boost_by_distance.select { |k, v| [:origin, :scale, :offset, :decay].include?(k) }
222 function_params[:origin] = function_params[:origin].reverse 222 function_params[:origin] = function_params[:origin].reverse
223 custom_filters << { 223 custom_filters << {
224 boost_by_distance[:function] => { 224 boost_by_distance[:function] => {
@@ -248,7 +248,7 @@ module Searchkick @@ -248,7 +248,7 @@ module Searchkick
248 if options[:order] 248 if options[:order]
249 order = options[:order].is_a?(Enumerable) ? options[:order] : {options[:order] => :asc} 249 order = options[:order].is_a?(Enumerable) ? options[:order] : {options[:order] => :asc}
250 # TODO id transformation for arrays 250 # TODO id transformation for arrays
251 - payload[:sort] = order.is_a?(Array) ? order : Hash[ order.map{|k, v| [k.to_s == "id" ? :_id : k, v] } ] 251 + payload[:sort] = order.is_a?(Array) ? order : Hash[order.map { |k, v| [k.to_s == "id" ? :_id : k, v] }]
252 end 252 end
253 253
254 # filters 254 # filters
@@ -263,14 +263,14 @@ module Searchkick @@ -263,14 +263,14 @@ module Searchkick
263 if options[:facets] 263 if options[:facets]
264 facets = options[:facets] || {} 264 facets = options[:facets] || {}
265 if facets.is_a?(Array) # convert to more advanced syntax 265 if facets.is_a?(Array) # convert to more advanced syntax
266 - facets = Hash[ facets.map{|f| [f, {}] } ] 266 + facets = Hash[facets.map { |f| [f, {}] }]
267 end 267 end
268 268
269 payload[:facets] = {} 269 payload[:facets] = {}
270 facets.each do |field, facet_options| 270 facets.each do |field, facet_options|
271 # ask for extra facets due to 271 # ask for extra facets due to
272 # https://github.com/elasticsearch/elasticsearch/issues/1305 272 # https://github.com/elasticsearch/elasticsearch/issues/1305
273 - size = facet_options[:limit] ? facet_options[:limit] + 150 : 100000 273 + size = facet_options[:limit] ? facet_options[:limit] + 150 : 100_000
274 274
275 if facet_options[:ranges] 275 if facet_options[:ranges]
276 payload[:facets][field] = { 276 payload[:facets][field] = {
@@ -300,7 +300,7 @@ module Searchkick @@ -300,7 +300,7 @@ module Searchkick
300 # offset is not possible 300 # offset is not possible
301 # http://elasticsearch-users.115913.n3.nabble.com/Is-pagination-possible-in-termsStatsFacet-td3422943.html 301 # http://elasticsearch-users.115913.n3.nabble.com/Is-pagination-possible-in-termsStatsFacet-td3422943.html
302 302
303 - facet_options.deep_merge!(where: options[:where].reject{|k| k == field}) if options[:smart_facets] == true 303 + facet_options.deep_merge!(where: options[:where].reject { |k| k == field }) if options[:smart_facets] == true
304 facet_filters = where_filters(facet_options[:where]) 304 facet_filters = where_filters(facet_options[:where])
305 if facet_filters.any? 305 if facet_filters.any?
306 payload[:facets][field][:facet_filter] = { 306 payload[:facets][field][:facet_filter] = {
@@ -318,7 +318,7 @@ module Searchkick @@ -318,7 +318,7 @@ module Searchkick
318 318
319 # intersection 319 # intersection
320 if options[:fields] 320 if options[:fields]
321 - suggest_fields = suggest_fields & options[:fields].map{|v| (v.is_a?(Hash) ? v.keys.first : v).to_s.split("^", 2).first } 321 + suggest_fields &= options[:fields].map { |v| (v.is_a?(Hash) ? v.keys.first : v).to_s.split("^", 2).first }
322 end 322 end
323 323
324 if suggest_fields.any? 324 if suggest_fields.any?
@@ -336,11 +336,11 @@ module Searchkick @@ -336,11 +336,11 @@ module Searchkick
336 # highlight 336 # highlight
337 if options[:highlight] 337 if options[:highlight]
338 payload[:highlight] = { 338 payload[:highlight] = {
339 - fields: Hash[ fields.map{|f| [f, {}] } ] 339 + fields: Hash[fields.map { |f| [f, {}] }]
340 } 340 }
341 341
342 if options[:highlight].is_a?(Hash) 342 if options[:highlight].is_a?(Hash)
343 - if tag = options[:highlight][:tag] 343 + if (tag = options[:highlight][:tag])
344 payload[:highlight][:pre_tags] = [tag] 344 payload[:highlight][:pre_tags] = [tag]
345 payload[:highlight][:post_tags] = [tag.to_s.gsub(/\A</, "</")] 345 payload[:highlight][:post_tags] = [tag.to_s.gsub(/\A</, "</")]
346 end 346 end
@@ -365,7 +365,7 @@ module Searchkick @@ -365,7 +365,7 @@ module Searchkick
365 end 365 end
366 366
367 if options[:type] || klass != searchkick_klass 367 if options[:type] || klass != searchkick_klass
368 - @type = [options[:type] || klass].flatten.map{|v| searchkick_index.klass_document_type(v) } 368 + @type = [options[:type] || klass].flatten.map { |v| searchkick_index.klass_document_type(v) }
369 end 369 end
370 end 370 end
371 371
@@ -430,7 +430,7 @@ module Searchkick @@ -430,7 +430,7 @@ module Searchkick
430 field = field.to_s 430 field = field.to_s
431 facet = response["facets"][field] 431 facet = response["facets"][field]
432 response["facets"][field]["terms"] = facet["terms"].first(limit) 432 response["facets"][field]["terms"] = facet["terms"].first(limit)
433 - response["facets"][field]["other"] = facet["total"] - facet["terms"].sum{|term| term["count"] } 433 + response["facets"][field]["other"] = facet["total"] - facet["terms"].sum { |term| term["count"] }
434 end 434 end
435 435
436 opts = { 436 opts = {
@@ -453,7 +453,7 @@ module Searchkick @@ -453,7 +453,7 @@ module Searchkick
453 453
454 if field == :or 454 if field == :or
455 value.each do |or_clause| 455 value.each do |or_clause|
456 - filters << {or: or_clause.map{|or_statement| {and: where_filters(or_statement)} }} 456 + filters << {or: or_clause.map { |or_statement| {and: where_filters(or_statement)} }}
457 end 457 end
458 else 458 else
459 # expand ranges 459 # expand ranges
@@ -507,7 +507,7 @@ module Searchkick @@ -507,7 +507,7 @@ module Searchkick
507 raise "Unknown where operator" 507 raise "Unknown where operator"
508 end 508 end
509 # issue 132 509 # issue 132
510 - if existing = filters.find{ |f| f[:range] && f[:range][field] } 510 + if (existing = filters.find { |f| f[:range] && f[:range][field] })
511 existing[:range][field].merge!(range_query) 511 existing[:range][field].merge!(range_query)
512 else 512 else
513 filters << {range: {field => range_query}} 513 filters << {range: {field => range_query}}
lib/searchkick/results.rb
@@ -21,7 +21,7 @@ module Searchkick @@ -21,7 +21,7 @@ module Searchkick
21 # results can have different types 21 # results can have different types
22 results = {} 22 results = {}
23 23
24 - hits.group_by{|hit, i| hit["_type"] }.each do |type, grouped_hits| 24 + hits.group_by { |hit, i| hit["_type"] }.each do |type, grouped_hits|
25 records = type.camelize.constantize 25 records = type.camelize.constantize
26 if options[:includes] 26 if options[:includes]
27 if defined?(NoBrainer::Document) && records < NoBrainer::Document 27 if defined?(NoBrainer::Document) && records < NoBrainer::Document
@@ -35,7 +35,7 @@ module Searchkick @@ -35,7 +35,7 @@ module Searchkick
35 35
36 # sort 36 # sort
37 hits.map do |hit| 37 hits.map do |hit|
38 - results[hit["_type"]].find{|r| r.id.to_s == hit["_id"].to_s } 38 + results[hit["_type"]].find { |r| r.id.to_s == hit["_id"].to_s }
39 end.compact 39 end.compact
40 else 40 else
41 hits.map do |hit| 41 hits.map do |hit|
@@ -54,7 +54,7 @@ module Searchkick @@ -54,7 +54,7 @@ module Searchkick
54 54
55 def suggestions 55 def suggestions
56 if response["suggest"] 56 if response["suggest"]
57 - response["suggest"].values.flat_map{|v| v.first["options"] }.sort_by{|o| -o["score"] }.map{|o| o["text"] }.uniq 57 + response["suggest"].values.flat_map { |v| v.first["options"] }.sort_by { |o| -o["score"] }.map { |o| o["text"] }.uniq
58 else 58 else
59 raise "Pass `suggest: true` to the search method for suggestions" 59 raise "Pass `suggest: true` to the search method for suggestions"
60 end 60 end
@@ -68,7 +68,7 @@ module Searchkick @@ -68,7 +68,7 @@ module Searchkick
68 each_with_hit.map do |model, hit| 68 each_with_hit.map do |model, hit|
69 details = {} 69 details = {}
70 if hit["highlight"] 70 if hit["highlight"]
71 - details[:highlight] = Hash[ hit["highlight"].map{|k, v| [(options[:json] ? k : k.sub(/\.analyzed\z/, "")).to_sym, v.first] } ] 71 + details[:highlight] = Hash[hit["highlight"].map { |k, v| [(options[:json] ? k : k.sub(/\.analyzed\z/, "")).to_sym, v.first] }]
72 end 72 end
73 [model, details] 73 [model, details]
74 end 74 end
@@ -140,16 +140,16 @@ module Searchkick @@ -140,16 +140,16 @@ module Searchkick
140 def results_query(records, grouped_hits) 140 def results_query(records, grouped_hits)
141 if records.respond_to?(:primary_key) && records.primary_key 141 if records.respond_to?(:primary_key) && records.primary_key
142 # ActiveRecord 142 # ActiveRecord
143 - records.where(records.primary_key => grouped_hits.map{|hit| hit["_id"] }).to_a 143 + records.where(records.primary_key => grouped_hits.map { |hit| hit["_id"] }).to_a
144 elsif records.respond_to?(:all) && records.all.respond_to?(:for_ids) 144 elsif records.respond_to?(:all) && records.all.respond_to?(:for_ids)
145 # Mongoid 2 145 # Mongoid 2
146 - records.all.for_ids(grouped_hits.map{|hit| hit["_id"] }).to_a 146 + records.all.for_ids(grouped_hits.map { |hit| hit["_id"] }).to_a
147 elsif records.respond_to?(:queryable) 147 elsif records.respond_to?(:queryable)
148 # Mongoid 3+ 148 # Mongoid 3+
149 - records.queryable.for_ids(grouped_hits.map{|hit| hit["_id"] }).to_a 149 + records.queryable.for_ids(grouped_hits.map { |hit| hit["_id"] }).to_a
150 elsif records.respond_to?(:unscoped) && records.all.respond_to?(:preload) 150 elsif records.respond_to?(:unscoped) && records.all.respond_to?(:preload)
151 # Nobrainer 151 # Nobrainer
152 - records.unscoped.where(:id.in => grouped_hits.map{|hit| hit["_id"] }).to_a 152 + records.unscoped.where(:id.in => grouped_hits.map { |hit| hit["_id"] }).to_a
153 else 153 else
154 raise "Not sure how to load records" 154 raise "Not sure how to load records"
155 end 155 end
lib/searchkick/tasks.rb
@@ -3,13 +3,13 @@ require &quot;rake&quot; @@ -3,13 +3,13 @@ require &quot;rake&quot;
3 namespace :searchkick do 3 namespace :searchkick do
4 4
5 desc "reindex model" 5 desc "reindex model"
6 - task :reindex => :environment do 6 + task reindex: :environment do
7 if ENV["CLASS"] 7 if ENV["CLASS"]
8 klass = ENV["CLASS"].constantize rescue nil 8 klass = ENV["CLASS"].constantize rescue nil
9 if klass 9 if klass
10 klass.reindex 10 klass.reindex
11 else 11 else
12 - abort "Could not find class: #{ENV["CLASS"]}" 12 + abort "Could not find class: #{ENV['CLASS']}"
13 end 13 end
14 else 14 else
15 abort "USAGE: rake searchkick:reindex CLASS=Product" 15 abort "USAGE: rake searchkick:reindex CLASS=Product"
@@ -20,7 +20,7 @@ namespace :searchkick do @@ -20,7 +20,7 @@ namespace :searchkick do
20 20
21 namespace :reindex do 21 namespace :reindex do
22 desc "reindex all models" 22 desc "reindex all models"
23 - task :all => :environment do 23 + task all: :environment do
24 Rails.application.eager_load! 24 Rails.application.eager_load!
25 Searchkick.models.each do |model| 25 Searchkick.models.each do |model|
26 puts "Reindexing #{model.name}..." 26 puts "Reindexing #{model.name}..."
searchkick.gemspec
1 # coding: utf-8 1 # coding: utf-8
2 -lib = File.expand_path('../lib', __FILE__) 2 +lib = File.expand_path("../lib", __FILE__)
3 $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 3 $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4 -require 'searchkick/version' 4 +require "searchkick/version"
5 5
6 Gem::Specification.new do |spec| 6 Gem::Specification.new do |spec|
7 spec.name = "searchkick" 7 spec.name = "searchkick"
8 spec.version = Searchkick::VERSION 8 spec.version = Searchkick::VERSION
9 spec.authors = ["Andrew Kane"] 9 spec.authors = ["Andrew Kane"]
10 spec.email = ["andrew@chartkick.com"] 10 spec.email = ["andrew@chartkick.com"]
11 - spec.description = %q{Intelligent search made easy}  
12 - spec.summary = %q{Searchkick learns what your users are looking for. As more people search, it gets smarter and the results get better. Itโ€™s friendly for developers - and magical for your users.} 11 + spec.description = "Intelligent search made easy"
  12 + spec.summary = "Searchkick learns what your users are looking for. As more people search, it gets smarter and the results get better. Itโ€™s friendly for developers - and magical for your users."
13 spec.homepage = "https://github.com/ankane/searchkick" 13 spec.homepage = "https://github.com/ankane/searchkick"
14 spec.license = "MIT" 14 spec.license = "MIT"
15 15
16 - spec.files = `git ls-files`.split($/) 16 + spec.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
17 spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } 17 spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18 spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) 18 spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19 spec.require_paths = ["lib"] 19 spec.require_paths = ["lib"]
test/facets_test.rb
@@ -79,7 +79,7 @@ class TestFacets &lt; Minitest::Test @@ -79,7 +79,7 @@ class TestFacets &lt; Minitest::Test
79 protected 79 protected
80 80
81 def store_facet(options) 81 def store_facet(options)
82 - Hash[ Product.search("Product", options).facets["store_id"]["terms"].map{|v| [v["term"], v["count"]] } ] 82 + Hash[Product.search("Product", options).facets["store_id"]["terms"].map { |v| [v["term"], v["count"]] }]
83 end 83 end
84 84
85 end 85 end
test/index_test.rb
@@ -75,24 +75,24 @@ class TestIndex &lt; Minitest::Test @@ -75,24 +75,24 @@ class TestIndex &lt; Minitest::Test
75 def test_bad_mapping 75 def test_bad_mapping
76 Product.searchkick_index.delete 76 Product.searchkick_index.delete
77 store_names ["Product A"] 77 store_names ["Product A"]
78 - assert_raises(Searchkick::InvalidQueryError){ Product.search "test" } 78 + assert_raises(Searchkick::InvalidQueryError) { Product.search "test" }
79 ensure 79 ensure
80 Product.reindex 80 Product.reindex
81 end 81 end
82 82
83 def test_missing_index 83 def test_missing_index
84 - assert_raises(Searchkick::MissingIndexError){ Product.search "test", index_name: "not_found" } 84 + assert_raises(Searchkick::MissingIndexError) { Product.search "test", index_name: "not_found" }
85 end 85 end
86 86
87 def test_unsupported_version 87 def test_unsupported_version
88 - raises_exception = lambda { |s| raise Elasticsearch::Transport::Transport::Error.new("[500] No query registered for [multi_match]") } 88 + raises_exception = ->(s) { raise Elasticsearch::Transport::Transport::Error.new("[500] No query registered for [multi_match]") }
89 Searchkick.client.stub :search, raises_exception do 89 Searchkick.client.stub :search, raises_exception do
90 - assert_raises(Searchkick::UnsupportedVersionError){ Product.search("test") } 90 + assert_raises(Searchkick::UnsupportedVersionError) { Product.search("test") }
91 end 91 end
92 end 92 end
93 93
94 def test_invalid_query 94 def test_invalid_query
95 - assert_raises(Searchkick::InvalidQueryError){ Product.search(query: {}) } 95 + assert_raises(Searchkick::InvalidQueryError) { Product.search(query: {}) }
96 end 96 end
97 97
98 if defined?(ActiveRecord) 98 if defined?(ActiveRecord)
test/reindex_v2_job_test.rb
@@ -3,7 +3,7 @@ require_relative &quot;test_helper&quot; @@ -3,7 +3,7 @@ require_relative &quot;test_helper&quot;
3 class TestReindexV2Job < Minitest::Test 3 class TestReindexV2Job < Minitest::Test
4 4
5 def setup 5 def setup
6 - skip if !defined?(ActiveJob) 6 + skip unless defined?(ActiveJob)
7 super 7 super
8 Searchkick.disable_callbacks 8 Searchkick.disable_callbacks
9 end 9 end
test/sql_test.rb
@@ -8,7 +8,7 @@ class TestSql &lt; Minitest::Test @@ -8,7 +8,7 @@ class TestSql &lt; Minitest::Test
8 end 8 end
9 9
10 def test_no_limit 10 def test_no_limit
11 - names = 20.times.map{|i| "Product #{i}" } 11 + names = 20.times.map { |i| "Product #{i}" }
12 store_names names 12 store_names names
13 assert_search "product", names 13 assert_search "product", names
14 end 14 end
@@ -57,7 +57,7 @@ class TestSql &lt; Minitest::Test @@ -57,7 +57,7 @@ class TestSql &lt; Minitest::Test
57 {name: "Product A", store_id: 1, in_stock: true, backordered: true, created_at: now, orders_count: 4, user_ids: [1, 2, 3]}, 57 {name: "Product A", store_id: 1, in_stock: true, backordered: true, created_at: now, orders_count: 4, user_ids: [1, 2, 3]},
58 {name: "Product B", store_id: 2, in_stock: true, backordered: false, created_at: now - 1, orders_count: 3, user_ids: [1]}, 58 {name: "Product B", store_id: 2, in_stock: true, backordered: false, created_at: now - 1, orders_count: 3, user_ids: [1]},
59 {name: "Product C", store_id: 3, in_stock: false, backordered: true, created_at: now - 2, orders_count: 2, user_ids: [1, 3]}, 59 {name: "Product C", store_id: 3, in_stock: false, backordered: true, created_at: now - 2, orders_count: 2, user_ids: [1, 3]},
60 - {name: "Product D", store_id: 4, in_stock: false, backordered: false, created_at: now - 3, orders_count: 1}, 60 + {name: "Product D", store_id: 4, in_stock: false, backordered: false, created_at: now - 3, orders_count: 1}
61 ] 61 ]
62 assert_search "product", ["Product A", "Product B"], where: {in_stock: true} 62 assert_search "product", ["Product A", "Product B"], where: {in_stock: true}
63 # date 63 # date
@@ -85,7 +85,7 @@ class TestSql &lt; Minitest::Test @@ -85,7 +85,7 @@ class TestSql &lt; Minitest::Test
85 assert_search "product", ["Product A", "Product C"], where: {user_ids: {all: [1, 3]}} 85 assert_search "product", ["Product A", "Product C"], where: {user_ids: {all: [1, 3]}}
86 assert_search "product", [], where: {user_ids: {all: [1, 2, 3, 4]}} 86 assert_search "product", [], where: {user_ids: {all: [1, 2, 3, 4]}}
87 # any / nested terms 87 # any / nested terms
88 - assert_search "product", ["Product B", "Product C"], where: {user_ids: {not: [2], in: [1,3]}} 88 + assert_search "product", ["Product B", "Product C"], where: {user_ids: {not: [2], in: [1, 3]}}
89 # not / exists 89 # not / exists
90 assert_search "product", ["Product D"], where: {user_ids: nil} 90 assert_search "product", ["Product D"], where: {user_ids: nil}
91 assert_search "product", ["Product A", "Product B", "Product C"], where: {user_ids: {not: nil}} 91 assert_search "product", ["Product A", "Product B", "Product C"], where: {user_ids: {not: nil}}
@@ -288,7 +288,7 @@ class TestSql &lt; Minitest::Test @@ -288,7 +288,7 @@ class TestSql &lt; Minitest::Test
288 def test_select 288 def test_select
289 store [{name: "Product A", store_id: 1}] 289 store [{name: "Product A", store_id: 1}]
290 result = Product.search("product", load: false, select: [:name, :store_id]).first 290 result = Product.search("product", load: false, select: [:name, :store_id]).first
291 - assert_equal %w[id name store_id], result.keys.reject{|k| k.start_with?("_") }.sort 291 + assert_equal %w[id name store_id], result.keys.reject { |k| k.start_with?("_") }.sort
292 assert_equal ["Product A"], result.name # this is not great 292 assert_equal ["Product A"], result.name # this is not great
293 end 293 end
294 294
test/suggest_test.rb
@@ -19,13 +19,13 @@ class TestSuggest &lt; Minitest::Test @@ -19,13 +19,13 @@ class TestSuggest &lt; Minitest::Test
19 19
20 def test_without_option 20 def test_without_option
21 store_names ["hi"] # needed to prevent ElasticsearchException - seed 668 21 store_names ["hi"] # needed to prevent ElasticsearchException - seed 668
22 - assert_raises(RuntimeError){ Product.search("hi").suggestions } 22 + assert_raises(RuntimeError) { Product.search("hi").suggestions }
23 end 23 end
24 24
25 def test_multiple_fields 25 def test_multiple_fields
26 store [ 26 store [
27 {name: "Shark", color: "Sharp"}, 27 {name: "Shark", color: "Sharp"},
28 - {name: "Shark", color: "Sharp"}, 28 + {name: "Shark", color: "Sharp"}
29 ] 29 ]
30 assert_suggest_all "shar", ["shark", "sharp"] 30 assert_suggest_all "shar", ["shark", "sharp"]
31 end 31 end
test/test_helper.rb
@@ -8,7 +8,7 @@ ENV[&quot;RACK_ENV&quot;] = &quot;test&quot; @@ -8,7 +8,7 @@ ENV[&quot;RACK_ENV&quot;] = &quot;test&quot;
8 8
9 Minitest::Test = Minitest::Unit::TestCase unless defined?(Minitest::Test) 9 Minitest::Test = Minitest::Unit::TestCase unless defined?(Minitest::Test)
10 10
11 -File.delete("elasticsearch.log") if File.exists?("elasticsearch.log") 11 +File.delete("elasticsearch.log") if File.exist?("elasticsearch.log")
12 Searchkick.client.transport.logger = Logger.new("elasticsearch.log") 12 Searchkick.client.transport.logger = Logger.new("elasticsearch.log")
13 13
14 I18n.config.enforce_available_locales = true 14 I18n.config.enforce_available_locales = true
@@ -26,7 +26,7 @@ if defined?(Mongoid) @@ -26,7 +26,7 @@ if defined?(Mongoid)
26 module BSON 26 module BSON
27 class ObjectId 27 class ObjectId
28 def <=>(other) 28 def <=>(other)
29 - self.data <=> other.data 29 + data <=> other.data
30 end 30 end
31 end 31 end
32 end 32 end
@@ -223,7 +223,7 @@ class Animal @@ -223,7 +223,7 @@ class Animal
223 searchkick \ 223 searchkick \
224 autocomplete: [:name], 224 autocomplete: [:name],
225 suggest: [:name], 225 suggest: [:name],
226 - index_name: -> { "#{self.name.tableize}-#{Date.today.year}" } 226 + index_name: -> { "#{name.tableize}-#{Date.today.year}" }
227 # wordnet: true 227 # wordnet: true
228 end 228 end
229 229
@@ -252,7 +252,7 @@ class Minitest::Test @@ -252,7 +252,7 @@ class Minitest::Test
252 end 252 end
253 253
254 def store_names(names, klass = Product) 254 def store_names(names, klass = Product)
255 - store names.map{|name| {name: name} }, klass 255 + store names.map { |name| {name: name} }, klass
256 end 256 end
257 257
258 # no order 258 # no order