Reputation: 149
I have a string that represents a file path, such as "/home/user/dir1/dir2/dir3/name.ext". Now I'd like to convert it to a legal URI (a string starting with "file://" and so on).
How do I do it in Ruby?
Upvotes: 6
Views: 4024
Reputation: 4735
Since Ruby 2.6.3 use can use URI::File
path = '/somewhere/on/your/drive'
URI::File.build([nil, path])
Upvotes: 3
Reputation: 4245
require 'uri'
uri = URI.join('file:///', '/home/user/dir1/dir2/dir3/name.ext')
=> #<URI::Generic:0x0000000263fcc0 URL:file:/home/user/dir1/dir2/dir3/name.ext>
uri.scheme
=> "file"
uri.path
=> "/home/user/dir1/dir2/dir3/name.ext"
uri.to_s
=> "file:/home/user/dir1/dir2/dir3/name.ext"
Upvotes: 6