ruby / uri

URI is a module providing classes to handle Uniform Resource Identifiers
https://ruby.github.io/uri/
Other
85 stars 46 forks source link

How to create file URI from file path (Support Request / Documentation Bug) #87

Open tonklon opened 1 year ago

tonklon commented 1 year ago

In https://github.com/ruby/uri/blob/bec5ef95cf6e378560f55fd6b0e9f1c139626670/lib/uri/file.rb#L50C1-L50C1 there is the following example of building a file URI:

uri3 = URI::File.build({:path => URI::escape('/path/my file.txt')})
uri3.to_s  # => "file:///path/my%20file.txt"

This example does not work anymore, since URI::escape() is gone. How are we supposed to replace this? Let's pretend we have a path on disk like '/home/username/Überraschung zum Geburtstag/🎂/ideas.md'

Using URI::encode_www_form_component

uri = URI::File.build(path: URI::encode_www_form_component("/home/username/Überraschung zum Geburtstag/🎂/ideas.md"))
# throws URI::InvalidComponentError, because the path_separators are encoded as well. And spaces are encoded as +

Using URI::encode_uri_component

uri = URI::File.build(path: URI::encode_uri_component("/home/username/Überraschung zum Geburtstag/🎂/ideas.md"))
# throws URI::InvalidComponentError, because the path_separators are encoded as well. Spaces are encoded as %20

The best I have come up with so far is using URI::Parser.new.escape:

uri = URI::File.build(path: URI::Parser.new.escape("/home/username/Überraschung zum Geburtstag/🎂/ideas.md"))
uri.to_s # => "file:///home/username/%C3%9Cberraschung%20zum%20Geburtstag/%F0%9F%8E%82/ideas.md"

Is this correct? Is this the intended way? Should the comment be updated? Or do we need to create a better way to encode paths.