Skip to content

Instantly share code, notes, and snippets.

@erikh
Created July 10, 2013 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikh/5965055 to your computer and use it in GitHub Desktop.
Save erikh/5965055 to your computer and use it in GitHub Desktop.
#
# :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