1

I'd like to convert the following PATH into a UNC path in Ruby.

C:/Users/bla/bla2/asdf-ut-script.js

Nakilon
  • 34,866
  • 14
  • 107
  • 142
wmitchell
  • 5,665
  • 10
  • 37
  • 62

1 Answers1

1

A UNC path requires that you know the name of the server and share, neither of which are present in your path, unless you're looking for something like:
\\localhost\C$\Users\bla\bla2\asdf-ut-script.js

If this is what you want:

def File.to_unc( path, server="localhost", share=nil )
  parts = path.split(File::SEPARATOR)
  parts.shift while parts.first.empty?
  if share
    parts.unshift share
  else
    # Assumes the drive will always be a single letter up front
    parts[0] = "#{parts[0][0,1]}$" 
  end
  parts.unshift server
  "\\\\#{parts.join('\\')}"
end

puts File.to_unc( "C:/Users/bla/bla2/asdf-ut-script.js" )
#=> \\localhost\C$\Users\bla\bla2\asdf-ut-script.js

puts File.to_unc( "C:/Users/bla/bla2/asdf-ut-script.js", 'filepile' )
#=> \\filepile\C$\Users\bla\bla2\asdf-ut-script.js

puts File.to_unc( "/bla/bla2/asdf-ut-script.js", 'filepile', 'HOME' )
#=> \\filepile\HOME\bla\bla2\asdf-ut-script.js
Phrogz
  • 296,393
  • 112
  • 651
  • 745