7

I am using Ruby and need to detect whether a directory is writeable before trying to create new files.

I have tried the following code, which correctly returns true/false depending on whether @path is a directory. However, it still returns true when there is no write permission to the @path folder.

  if File.directory?(@path) && File.writable?(@path)
    #is a writeable directory
    true
  else
    #is not a writeable directory
    false
  end

I have looked at the help for the File and Dir classes and cannot see any method that allows me to check directory write permissions. Is there a way?

I only need it work on Windows, using Ruby 1.9.3.

SimonMayer
  • 4,719
  • 4
  • 33
  • 45

2 Answers2

3

For Windows you want the File.attributes or File.readonly? methods from the win32-file gem.

And you should consider contributing to Daniel Berger, as without his win32- gems Ruby on Windows would be a far more hostile place.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • It seems that File.attributes will only return `["directory", "indexed"]` for a directory where write permission has been denied. Similarly, File.readonly? returns false. When used on a file, both the #attributes and #readonly? methods work as expected. – SimonMayer Jan 26 '12 at 16:08
  • @SimonMayer Very odd. I've never used this, and I'm not on Windows now to test, but my experience is that the win32- gems are very reliable. Since this is documented explicitly as applying to directories as well, I wonder: are you _sure_ that your directory's permissions are what you think they are? – Phrogz Jan 26 '12 at 16:52
  • I'm currently only in a position to test a rather strange situation, but as it can legitimately occur, I'd like to detect it anyway. I have created a new local folder and have explicitly denied "write" permissions for my user (and also the Administrator user to be sure). So, unusually, I am the owner of the directory, but cannot write to it. This is definitely preventing Ruby from creating and writing a file using `File.open("...", "w+")`, because as soon as I remove the write deny, the file can be created/edited. Perhaps #attributes only returns "readonly" for files and not directories. – SimonMayer Jan 26 '12 at 17:24
0

You might be able to do it by using world_writable?(filename)

http://ruby-doc.org/core-1.9.3/File.html#method-c-world_writable-3F

Yoann Le Touche
  • 1,280
  • 9
  • 13
  • This isn't working. It is returning nil in all situations. I have tested it by writing a new file to the directory and reading its contents back again. `code directory = "C:" + File::SEPARATOR + "1234" puts File.directory?(directory).inspect puts File.world_writable?(directory).inspect File.open(directory + File::SEPARATOR + "newfile.txt", "w+"){|f| f.write "FileContents"} File.open(directory + File::SEPARATOR + "newfile.txt", "r"){|f| puts f.read }` – SimonMayer Jan 26 '12 at 10:54