Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URI encoding not working

On a rails app, I need to parse uris

a = 'some file name.txt'
URI(URI.encode(a)) # works

b = 'some filename with :colon in it.txt'
URI(URI.encode(b)) # fails URI::InvalidURIError: bad URI(is not URI?): 

How can I safely pass a file name to URI that contains special characters? Why doesn't encode work on colon?

like image 793
shankardevy Avatar asked Dec 12 '22 12:12

shankardevy


2 Answers

URI.escape (or encode) takes an optional second parameter. It's a Regexp matching all symbols that should be escaped. To escape all non-word characters you could use:

URI.encode('some filename with :colon in it.txt', /\W/)
#=> "some%20filename%20with%20%3Acolon%20in%20it%2Etxt"

There are two predefined regular expressions for encode:

URI::PATTERN::UNRESERVED  #=> "\\-_.!~*'()a-zA-Z\\d"
URI::PATTERN::RESERVED    #=> ";/?:@&=+$,\\[\\]"
like image 84
Stefan Avatar answered Dec 22 '22 19:12

Stefan


require 'uri'

url = "file1:abc.txt"
p URI.encode_www_form_component url

--output:--
"file1%3Aabc.txt"


p URI(URI.encode_www_form_component url)

--output:--
#<URI::Generic:0x000001008abf28 URL:file1%3Aabc.txt>


p URI(URI.encode url, ":")

--output:--
#<URI::Generic:0x000001008abcd0 URL:file1%3Aabc.txt>

Why doesn't encode work on colon?

Because encode/escape is broken.

like image 45
7stud Avatar answered Dec 22 '22 20:12

7stud