DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Convert A Conditions Hash To A SQL LIKE Conditions Array

01.15.2009
| 9479 views |
  • submit to reddit
        Inspired by http://snippets.dzone.com/posts/show/4734

USAGE
my_hash = {name => 'foo', location => 'bar'} 
my_hash.to_like_conditions # returns ["name LIKE ? and location LIKE ?", "%foo%", "%bar%"]

class Hash
  def to_like_conditions
    conditions = [self.keys.map{|k| "#{k} LIKE ?" }.join(" AND ")]
    conditions << self.values.map{|v| "%#{v}%" }
    conditions.flatten
  end
end