From 6c7f5bdc899d01c77bf65ff62423eb285c3c1eaf Mon Sep 17 00:00:00 2001 From: Michael Narayan Date: Mon, 19 Aug 2013 08:37:27 -0400 Subject: [PATCH] Enable graceful handling of Searchlight::Search::searches sans DB Enable users to gracefully handle the eager-loading of a Searchlight::Search class with a call to ::searches prior to DB creation (e.g. during a call to `rake assets:precompile`) by monkey-patching Searchlight::Search::model_has_db_attribute? --- lib/searchlight/adapters/active_record.rb | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/searchlight/adapters/active_record.rb b/lib/searchlight/adapters/active_record.rb index c78e64c..412c761 100644 --- a/lib/searchlight/adapters/active_record.rb +++ b/lib/searchlight/adapters/active_record.rb @@ -20,7 +20,7 @@ def searches(*attribute_names) eval_string = attribute_names.map { |attribute_name| model_class = model_class_for(search_target) - if model_class_for(search_target).columns_hash.keys.include?(attribute_name.to_s) + if model_has_db_attribute?(attribute_name.to_s) <<-UNICORN_BILE def search_#{attribute_name} @@ -40,6 +40,25 @@ def search_#{attribute_name} @ar_searches_module.module_eval(eval_string, __FILE__, __LINE__) end + + # The idea here is to provide a means to allow users to bypass the check if it causes problems (e.g. during + # `rake assets:precompile` if the DB has yet to be created). To bypass this, a user could monkey patch as + # follows: + # + # module Searchlight::Adapters::ActiveRecord::Search + # def model_has_db_attribute?(attribute_name) + # model_class_for(search_target).columns_hash.keys.include?(attribute_name) + # rescue StandardError + # true + # end + # end + # + # Alternatively, they could monkey-patch Searchlight::Adapters::ActiveRecord::Search::model_has_db_attribute + # to simply always return true, though they would then not get the benefit of the improved error messaging. + # + def model_has_db_attribute?(attribute_name) + model_class_for(search_target).columns_hash.keys.include?(attribute_name) + end end protected