Skip to content

Instantly share code, notes, and snippets.

@rscarvalho
Created June 16, 2010 18:32
Show Gist options
  • Save rscarvalho/441081 to your computer and use it in GitHub Desktop.
Save rscarvalho/441081 to your computer and use it in GitHub Desktop.
module CustomSearch
mattr_accessor :registered_classes
def self.search(qstring)
results = {}
self.registered_classes.each do |klass|
results[klass.name] = klass.on_index(qstring)
end
results
end
def self.included(base)
base.send :include, InstanceMethods
base.send :extend, ClassMethods
end
module ClassMethods
def use_as_index(*columns)
CustomSearch.registered_classes ||= []
CustomSearch.registered_classes << self unless CustomSearch.registered_classes.include?(self) # nesse caso, self vai ser a classe, nao a instancia
@search_columns = columns
self.send :named_scope, :on_index, proc { |text| {:conditions => ["lower(search_index) like lower(?)", "%#{text}%"]} }
self.send :before_save, :update_index
end
def search_columns
@search_columns ||= []
end
def rebuild_indices
find(:all).each do |obj|
obj.send :update_index
obj.save
end
end
end
module InstanceMethods
def update_index
self.search_index = self.class.search_columns.map{ |col| send(col) }.join(" ").chomp
end
protected :update_index
end
end
ActiveRecord::Base.send :include, CustomSearch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment