Skip to content

Commit

Permalink
Avoid overwriting existing search methods
Browse files Browse the repository at this point in the history
  • Loading branch information
pat committed Jul 7, 2024
1 parent 8ced2ef commit 7973cbf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
23 changes: 19 additions & 4 deletions lib/thinking_sphinx/active_record/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ module ThinkingSphinx::ActiveRecord::Base
extend ActiveSupport::Concern

included do
# Avoid method collisions for public Thinking Sphinx methods added to all
# ActiveRecord models. The `sphinx_`-prefixed versions will always exist,
# and the non-prefixed versions will be added if a method of that name
# doesn't already exist.
#
# If a method is overwritten later by something else, that's also fine - the
# prefixed versions will still be there.
class_module = ThinkingSphinx::ActiveRecord::Base::ClassMethods
class_module.public_instance_methods.each do |method_name|
short_method = method_name.to_s.delete_prefix("sphinx_").to_sym
next if methods.include?(short_method)

define_singleton_method(short_method, method(method_name))
end

if ActiveRecord::VERSION::STRING.to_i >= 5
[
::ActiveRecord::Reflection::HasManyReflection,
Expand All @@ -25,19 +40,19 @@ def extensions
end

module ClassMethods
def facets(query = nil, options = {})
def sphinx_facets(query = nil, options = {})
merge_search ThinkingSphinx.facets, query, options
end

def search(query = nil, options = {})
def sphinx_search(query = nil, options = {})
merge_search ThinkingSphinx.search, query, options
end

def search_count(query = nil, options = {})
def sphinx_search_count(query = nil, options = {})
search_for_ids(query, options).total_entries
end

def search_for_ids(query = nil, options = {})
def sphinx_search_for_ids(query = nil, options = {})
ThinkingSphinx::Search::Merger.new(
search(query, options)
).merge! nil, :ids_only => true
Expand Down
7 changes: 7 additions & 0 deletions spec/acceptance/searching_within_a_model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@
expect(Album.search(:indices => ['album_real_core']).first).
to eq(album)
end

it "is available via a sphinx-prefixed method" do
article = Article.create! :title => 'Pancakes'
index

expect(Article.sphinx_search.first).to eq(article)
end
end

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

0 comments on commit 7973cbf

Please sign in to comment.