Ruby 1.9.3 add unsafe characters to URI.escape
escaping, ruby, ruby-1.9.3, sinatra, uri
Solution
URI#escape is not what you are looking for. You want CGI#escape:
require 'cgi'
CGI.escape("foo_<_>_&_3_#_/_+_%_bar")
# => "foo_%3C_%3E_%26_3_%23_%2F_%2B_%25_bar"
This will properly encode it to allow Sinatra to retrieve it.
Problem
I am using Sinatra and get parameters from the url using the `get '/foo/:bar' {}` method. Unfortunately, the value in `:bar` can contain nasty things like `/` which leads to an 404, since no route matches `/foo/:bar/baz`/. I use `URI.escape` to escape the URL paramter, but it considers `/` valid a valid character. As it is mentioned here this is because the default Regexp to check against does not differentiate between unsafe and reserved characters. I would like to change this and did this: ``` URI.escape("foo_<_>_&_3_#_/_+_%_bar", Regexp.union(URI::REGEXP::UNSAFE, '/')) ``` just to test it. `URI::REGEXP::UNSAFE` is the default regexp to match against according to the Ruby 1.9.3 Documentaton: ``` escape(*arg) Synopsis URI.escape(str [, unsafe]) Args str String to replaces in. unsafe Regexp that matches all symbols that must be replaced with codes. By default uses REGEXP::UNSAFE. When this argument is a String, it represents a character set. Description Escapes the string, replacing all unsafe characters with codes. ``` Unfortunatelly I get this error: ``` uninitialized constant URI::REGEXP::UNSAFE ``` And as this GitHub Issue suggests, this Regexp was removed from Ruby with 1.9.3. Unfortunately, the `URI` modules documentation is generally kind of bad, but I really cannot figure this out. Any hints? Thanks in advance!