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?
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 #=> ";/?:@&=+$,\\[\\]"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With