Combining and Removing Ruby URIs

I have a URI object.

require 'uri'
uri = URI.parse 'http://example.com'

I need to combine some path to this URI.

path = URI.escape('/?foo[123]=5')
uri.merge!(path)

And getting the exception:

URI::InvalidURIError: bad URI(is not URI?): /?foo[123]=5

This is because some characters in the path are considered unsafe ("[" and "]"), but these characters are not deleted by URI.escape.

I solve this problem using two calls to URI.escape:

path = URI.escape(URI.escape('/?foo[123]=5'), '[]')
uri.merge!(path)

Question: Why does URI.escape not perform this default escaping?

Or maybe there is a better way to do this?

+3
source share
2 answers
+1
source

Use CGI.escapeinstead URI.escape:

require 'uri'
require 'cgi'
uri = URI.parse 'http://example.com'    
path = CGI.escape('/?foo[123]=5')
uri.merge!(path) #=> #<URI::HTTP:0x00000002947918 URL:http://example.com/%2F%3Ffoo%5B123%5D%3D5>
+1
source

Source: https://habr.com/ru/post/1793581/


All Articles