1

I am about to do a similar curl call like this:

curl https://api.mapbox.com/geocoding/v5/mapbox.places/1600+pennsylvania+ave+nw.json

When I enter my own address, it looks like this: 1600 pennsylvania ave nw. I tried to convert the white spaces to the + characters with using the URI.encode method:

address = URI.encode(full_address)

But the result is 1600%20pennsylvania%20ave%20nw, which, after all, seems to be a correct output, however it doesn't solve my problem.

As a possible solution is to manually convert and replace every character, but is there a better solution?

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
user984621
  • 46,344
  • 73
  • 224
  • 412

3 Answers3

3

You want

CGI.escape

instead. This probably converts a string so you can send it as an html parameter, ex:

CGI.escape "http://something that needs to be encoded"
=> "http%3A%2F%2Fsomething+that+needs+to+be+encoded"

Also see What's the difference between URI.escape and CGI.escape?

Community
  • 1
  • 1
Pascal
  • 8,464
  • 1
  • 20
  • 31
1

Break down the problem:

require 'uri'

path, filename = File.split('/geocoding/v5/mapbox.places/1600 pennsylvania ave nw.json')

URI paths are file paths to a resource, so you can use File.split to get the path and filename.

uri = URI.parse('https://api.mapbox.com')
uri.path = [path, URI.encode_www_form_component(filename)].join('/')

Rebuild the URI's path from the path and the encoded filename, which gives you:

uri.to_s
# => "https://api.mapbox.com/geocoding/v5/mapbox.places/1600+pennsylvania+ave+nw.json"

It seems to me that using %20 should be the right way to encode spaces in a path, but that would be determined by how they wrote their code.

You could use gsub if you're only dealing with converting spaces to +, but that'd miss necessary encoding if other characters were present that required it. URI follows the RFC which gsub wouldn't unless you wrote a lot more code.

I'd recommend looking at Addressable::URI also. It's a very full-featured gem for processing URIs.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

An easy way would be to use String#gsub, but I suggest to do this for the file name/your address only not for the whole url:

"1600 pennsylvania   ave     nw.json".squeeze(" ").gsub(" ", "+")
# => "1600+pennsylvania+ave+nw.json"
guitarman
  • 3,290
  • 1
  • 17
  • 27