Skip to content

Instantly share code, notes, and snippets.

@robacarp
Created December 21, 2011 18:16
Show Gist options
  • Save robacarp/1507053 to your computer and use it in GitHub Desktop.
Save robacarp/1507053 to your computer and use it in GitHub Desktop.
Rails Model Searchable Superclass
#a quick whipped full-text search superclass to help make queries appear out of nowhere for fun and profit
# if you're reading this thinking 'why?' you are right and you should probably just replace this paradigm
# with actual logic D:
class Searchable < ActiveRecord::Base
class << self
@@searches_on = {}
def searches_on *fields
cls = self.to_s.to_sym
unless @@searches_on.include? cls
@@searches_on[cls] = []
end
@@searches_on[cls] << fields
@@searches_on[cls].flatten!
end
def search search, limit = nil
where = '0'
like = '%' + search.gsub(' ','%') + '%'
@@searches_on[self.to_s.to_sym].each do |field|
field = field.to_s
unless self.columns_hash.include? field
raise NameError, "#{field} is not a valid column on #{self}"
end
if [:integer, :decimal, :float].include? self.columns_hash[ field.to_s ].type
where += ' or ' + self.arel_table[field].eq( search ).to_sql
else
where += ' or ' + self.arel_table[field].matches( like ).to_sql
end
end
if limit.nil?
self.where( where )
else
self.where( where ).limit( limit )
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment