Created
July 10, 2013 09:54
-
-
Save erikh/5965055 to your computer and use it in GitHub Desktop.
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
# | |
# :call-seq: | |
# escape( str ) | |
# escape( str, unsafe ) | |
# | |
# == Args | |
# | |
# +str+:: | |
# String to make safe | |
# +unsafe+:: | |
# Regexp to apply. Defaults to self.regexp[:UNSAFE] | |
# | |
# == Description | |
# | |
# constructs a safe String from +str+, removing unsafe characters, | |
# replacing them with codes. | |
# | |
def escape(str, unsafe = @regexp[:UNSAFE]) | |
unless unsafe.kind_of?(Regexp) | |
# perhaps unsafe is String object | |
unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false) | |
end | |
str.gsub(unsafe) do | |
us = $& | |
tmp = '' | |
us.each_byte do |uc| | |
tmp << sprintf('%%%02X', uc) | |
end | |
tmp | |
end.force_encoding(Encoding::US_ASCII) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment