diff --git a/lib/thinking_sphinx/active_record/base.rb b/lib/thinking_sphinx/active_record/base.rb index 6d6c882e..ebc656ad 100644 --- a/lib/thinking_sphinx/active_record/base.rb +++ b/lib/thinking_sphinx/active_record/base.rb @@ -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, @@ -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 diff --git a/spec/acceptance/searching_within_a_model_spec.rb b/spec/acceptance/searching_within_a_model_spec.rb index d9516706..b05ce8ea 100644 --- a/spec/acceptance/searching_within_a_model_spec.rb +++ b/spec/acceptance/searching_within_a_model_spec.rb @@ -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