Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Searchable
- def self.included(model)
- model.send(:extend, ClassMethods)
- model.class_eval do
- class_inheritable_accessor(:search_indexes)
- self.search_indexes = []
- end
- end
- module ClassMethods
- def search(query, options = {})
- conds = search_indexes.map{|idx| "#{idx}_search_index @@ plainto_tsquery(?)" }
- conds_array = [conds.join(" OR ")]
- search_indexes.size.times{ conds_array << escape_string(query) }
- all(options.merge(:conditions => conds_array))
- end
- private
- def escape_string(str)
- str.gsub(/([\0\n\r\032\'\"\\])/) do
- case $1
- when "\0" then "\\0"
- when "\n" then "\\n"
- when "\r" then "\\r"
- when "\032" then "\\Z"
- when "'" then "''"
- else "\\"+$1
- end
- end
- end
- end
- end
Add Comment
Please, Sign In to add comment