How can I detect whether a directory is writeable in Ruby
Asked Answered
G

2

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.

Galvanize answered 26/1, 2012 at 10:14 Comment(0)
U
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.

Uranyl answered 26/1, 2012 at 11:41 Comment(3)
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.Galvanize
@Galvanize 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?Uranyl
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.Galvanize
C
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

Crest answered 26/1, 2012 at 10:23 Comment(1)
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 }Galvanize

© 2022 - 2024 — McMap. All rights reserved.