Abstracting a search feature


#1

Dear Railers,

I’m trying to design a Search controller that will search my social
network website for Friends and Colleagues. However, I would like to
have some kind of encapsulation so that the Friend and Colleagues models
are responsible for performing their own searches, returning the results
to the Search, formatted according to their own separate views.

I think this is the right way to do things because these two different
models would be searching over different columns and returning different
forms of results (Colleagues might have a ‘workplace’, for example).
Also, this would make the system more extensible in the future, if I
need to add a Classmate object etc.

My question is simply, what’s the best way to do this? I am new to Ruby
and Rails, so I am not sure how the classes can interact, how I should
be passing around the search parameters and returning results with
set-specific views. Also I am worried that if both the Friend and
Colleague models are performing the search themselves, this would
violate the DRY principle.

Any help would be much appreciated,

Limbo


#2

Does anyone have any suggestions at all? :frowning:

Limbo


#3

Does anyone have any suggestions at all? :frowning:
I just found some old code I wrote that adds a basic search method to
active record. You’ll probably want to extend it (add fix bugs!) but
hopefully it’ll give you a starting point and show you how you can
approach this problem.

module ActiveRecord
class Base
def self.search(keywords)
keywords = keywords.split(" ")
sql_conditions = “”

  keywords.each do |word|
    sql_conditions << "("

    columns.each do |column|
      sql_conditions << "#{column.name} LIKE '%#{word}%' OR " if

column.type == :string
end

    sql_conditions.gsub!(/OR $/, '')
    sql_conditions << ") AND "
  end
  sql_conditions.gsub!(/ AND $/, '')

  find(:all, :conditions => sql_conditions)
end

end
end

Stick that in a file called active_record_extensions.rb (or something)
and save it to lib/. You’ll need add a require line to your
environment.rb:
require ‘lib/active_record_extensions’

You should then be able to do a basic search like this:
ClassMate.search(“stephen bartholomew”)

Hope that helps,

Steve