Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting file path to URI

Tags:

ruby

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?

like image 642
ori Avatar asked May 13 '12 12:05

ori


2 Answers

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"
like image 120
Flexoid Avatar answered Sep 22 '22 05:09

Flexoid


Since Ruby 2.6.3 use can use URI::File

path = '/somewhere/on/your/drive'
URI::File.build([nil, path])
like image 25
Daniel Avatar answered Sep 24 '22 05:09

Daniel