Skip to content

Instantly share code, notes, and snippets.

@raggi
Created September 27, 2011 21:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raggi/1246303 to your computer and use it in GitHub Desktop.
Save raggi/1246303 to your computer and use it in GitHub Desktop.
YOU WON'T (escape likes)
module EscapeLike
# Escape SQL LIKE arguments. N.B. This should be combined with use of the
# ESCAPE parameter also. See:
# http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
#
# pattern = escape_like(params[:pattern]) << '%'
# query = where(["name LIKE ? ESCAPE ?", pattern, '\\'])
#
# By default this method uses MySQLs default escape, backslash.
# Unfortunately, this can get exceedingly confusing in output. As soon as
# debugging is required, it is strongly recommended that users swap out and
# use '=' or some other character instead, to avoid trying to understand
# triple escaping.
def escape_like(value, escape = '\\')
escaped_like = value.dup
escaped_like.gsub!(escape, escape * 2)
escaped_like.gsub!("%", "#{escape}%")
escaped_like.gsub!("_", "#{escape}_")
escaped_like
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment