views:

102

answers:

2

I am using search logic to filter results on company listing page. The user is able to specify any number of parameters using a variety of named URLs. For example:

/location/mexico
/sector/technology
/sector/financial/location/argentina

Results in the following respectively:

params[:location] == 'mexico'
params[:sector] == 'technology'
params[:sector] == 'financial' and params[:location] == 'argentina'

I am now trying to cleanup or 'DRY' my model code. Currently I have:

def self.search(params)
    ...
    if params[:location]
        results = results.location_permalink_equals params[:location] if results
        results = Company.location_permalink_equals params[:location] unless results
    end
    if params[:sector]
        results = results.location_permalink_equals params[:sector] if results
        results = Company.location_permalink_equals params[:sector] unless results
    end
    ...
end

I don't like repeating the searchs. Any suggestions? Thanks.


+1  A: 

This is how I would write it:

[params[:location], params[:sector]].reject(&:nil?).each do |q|
  results = (results ? results : Company).location_permalink_equals q
end

There's plenty of other ways, just an idea. Has the benefit of making it easy to add say params[:street] or something.

Jakub Hampl
hurikhan77
Good ideas. I like `reject nil` as it's immediately clear what it does. `values_at` is great, especially if there were more params.
Jakub Hampl
+1  A: 

I don't think you can really DRY that up much when sticking to SearchLogic... I'd suggest to refine your routes to directly emit *_permalink as parameter names and do something like this:

Company.all :conditions => params.slice(:location_permalink, :sector_permalink)

or

Company.find :all, :conditions => params.slice(:location_permalink, :sector_permalink)

Documentation link: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Hash/Slice.html

hurikhan77