Created
September 27, 2011 21:31
-
-
Save raggi/1246303 to your computer and use it in GitHub Desktop.
YOU WON'T (escape likes)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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