Convert string with white space into URL

Steve picture Steve · Jun 27, 2010 · Viewed 14.1k times · Source

I'm using ruby and googles reverse geocode yql table to ideally automate some search query I have. The problem I hit is turning the query into a legal url format. The issue is that the encoding I'm using is returning illegal urls. The query I'm running is as follows

query="select * from google.geocoding where q='40.714224,-73.961452'" 
pQuery= CGI::escape(query)

The eventual output for the processed query looks like this

http://query.yahooapis.com/v1/public/yql?q=select+%2A+from+google.geocoding+where+q%3D%2740.3714224%2C--73.961452%27+format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

Alas the url is illegal. When checking what the query shoud look like in the YQL console I get the following

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.geocoding%20where%20q%3D%2240.714224%2C-73.961452%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

As you can hopefully see :), the encoding is all wrong. I was wondering does anyone know how I can go about generating correct urls.

Answer

Jörg W Mittag picture Jörg W Mittag · Jun 27, 2010

If you want to escape a URI, you should use URI::escape:

require 'uri'

URI.escape("select * from google.geocoding where q='40.714224,-73.961452'")
# => "select%20*%20from%20google.geocoding%20where%20q='40.714224,-73.961452'"