In Ruby/Rails, how can I encode/escape special characters in URLs?

jpw picture jpw · Feb 11, 2011 · Viewed 49.6k times · Source

How do I encode or 'escape' the URL before I use OpenURI to open(url)?

We're using OpenURI to open a remote url and return the xml:

getresult = open(url).read

The problem is the URL contains some user-input text that contains spaces and other characters, including "+", "&", "?", etc. potentially, so we need to safely escape the URL. I saw lots of examples when using Net::HTTP, but have not found any for OpenURI.

We also need to be able to un-escape a similar string we receive in a session variable, so we need the reciprocal function.

Answer

Ernest picture Ernest · Nov 29, 2012

Don't use URI.escape as it has been deprecated in 1.9.

Rails' Active Support adds Hash#to_query:

 {foo: 'asd asdf', bar: '"<#$dfs'}.to_query
 # => "bar=%22%3C%23%24dfs&foo=asd+asdf"

Also, as you can see it tries to order query parameters always the same way, which is good for HTTP caching.