Search code examples
rubyurlencodeopen-uri

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


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.


Solution

  • Ruby has the built-in URI library, and the Addressable gem, in particular Addressable::URI

    I prefer Addressable::URI. It's very full featured and handles the encoding for you when you use the query_values= method.

    I've seen some discussions about URI going through some growing pains so I tend to leave it alone for handling encoding/escaping until these things get sorted out: