Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I address a UNC path in Ruby on Windows?

Tags:

windows

ruby

unc

I'm trying to access a UNC share via irb on Windows. In the Windows shell it would be

\\server\share

I tried escaping all of the backslashes.

irb(main):016:0> Dir.entries '\\\\server\share'
Errno::ENOENT: No such file or directory - \\server\share

and using the IP address instead of the name

irb(main):017:0> Dir.entries '\\\\192.168.10.1\share'
Errno::ENOENT: No such file or directory - \\192.168.10.1\share
like image 571
Sven Avatar asked Oct 22 '10 09:10

Sven


2 Answers

Try to escape '\' with another '\'

Dir.entries('\\\\\\\\192.168.10.1\\\\share')
like image 142
ILog Avatar answered Sep 22 '22 01:09

ILog


Ruby interprets paths in a POSIX way, meaning you should use forward slashes when possible.

//server/share

The trailing slash is unnecessary, just like in native Windows. You can use backslashes, but they have to be escaped with another backslash.

\\\\server\\share

I'd only recommend that when you're passing UNC paths from native programs directly and can't transform them. When I'm mixing Ruby/Windows paths, like in a build script that uses Ruby methods and native Windows apps, which each require different paths, I'll use some helpers:

def windows_path(value)
  value.gsub '/', '\\'
end

def posix_path(value)
  value.gsub '\\', '/'
end

Always enclose your paths in single quotes, if they're literal, or double-quotes if you're interpolating. Forward slashes tell Ruby to start interpreting a regex. This is a common error for me in irb.

irb> File.exists? //server/share
SyntaxError: (irb):2: unknown regexp options - rvr
like image 37
Anthony Mastrean Avatar answered Sep 22 '22 01:09

Anthony Mastrean