Skip to content

Commit 7973cbf

Browse files
committed
Avoid overwriting existing search methods
1 parent 8ced2ef commit 7973cbf

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

lib/thinking_sphinx/active_record/base.rb

+19-4
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,21 @@ module ThinkingSphinx::ActiveRecord::Base
44
extend ActiveSupport::Concern
55

66
included do
7+
# Avoid method collisions for public Thinking Sphinx methods added to all
8+
# ActiveRecord models. The `sphinx_`-prefixed versions will always exist,
9+
# and the non-prefixed versions will be added if a method of that name
10+
# doesn't already exist.
11+
#
12+
# If a method is overwritten later by something else, that's also fine - the
13+
# prefixed versions will still be there.
14+
class_module = ThinkingSphinx::ActiveRecord::Base::ClassMethods
15+
class_module.public_instance_methods.each do |method_name|
16+
short_method = method_name.to_s.delete_prefix("sphinx_").to_sym
17+
next if methods.include?(short_method)
18+
19+
define_singleton_method(short_method, method(method_name))
20+
end
21+
722
if ActiveRecord::VERSION::STRING.to_i >= 5
823
[
924
::ActiveRecord::Reflection::HasManyReflection,
@@ -25,19 +40,19 @@ def extensions
2540
end
2641

2742
module ClassMethods
28-
def facets(query = nil, options = {})
43+
def sphinx_facets(query = nil, options = {})
2944
merge_search ThinkingSphinx.facets, query, options
3045
end
3146

32-
def search(query = nil, options = {})
47+
def sphinx_search(query = nil, options = {})
3348
merge_search ThinkingSphinx.search, query, options
3449
end
3550

36-
def search_count(query = nil, options = {})
51+
def sphinx_search_count(query = nil, options = {})
3752
search_for_ids(query, options).total_entries
3853
end
3954

40-
def search_for_ids(query = nil, options = {})
55+
def sphinx_search_for_ids(query = nil, options = {})
4156
ThinkingSphinx::Search::Merger.new(
4257
search(query, options)
4358
).merge! nil, :ids_only => true

spec/acceptance/searching_within_a_model_spec.rb

+7
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,13 @@
9292
expect(Album.search(:indices => ['album_real_core']).first).
9393
to eq(album)
9494
end
95+
96+
it "is available via a sphinx-prefixed method" do
97+
article = Article.create! :title => 'Pancakes'
98+
index
99+
100+
expect(Article.sphinx_search.first).to eq(article)
101+
end
95102
end
96103

97104
describe 'Searching within a model with a realtime index', :live => true do

0 commit comments

Comments
 (0)