Today I was exploring some of the useful methods Ruby has available to work with the File System.

Does my file, or directory exist?

Given that you have a filename or directory name how would you check if it exists? First let’s see how we can check if the file exists? We are going to use the built-in File class in Ruby so no need for any require statements.

We see that the File class has a ‘file?’ class method that will return true or false based on whether the file exists or if it doesn’t exist.

Now let’s do the same with a directory.

Great, so we can use the same methods that we use to test the existence of a directory to check a file’s existence. However, this is also not so great, reading this code won’t give us any indication that we are checking a file or a directory. A more explicit way of doing this, is by calling the ‘directory?’ method that is also a class level method on File.

What sort of access do I have to a file or directory?

Next how do we check what sort of access we have on this file. Ruby has three different methods that allow us to determine the level of access to a file. These methods are very Ruby centric but are still usable across platforms.

The methods are pretty straight-forward, call ‘executable?’, ‘readable?’ or ‘writable?’ to get a response on what sort of permission you have on a particular file or directory.

How do I change the permissions of a file?

Now let’s change the permissions on the file. Here are the different Unix permission bits, we are going to use them in this example.

Whilst researching file permissions in Ruby, I found that many people suggest creating a class with these various bits as constants. I am going to go ahead and do that as I will never remember these different values.

We are onto a good thing here. In Ruby, we will call the ‘chmod’ method which if you are familiar with Unix changes permissions on files and directories.

What I found is that the permissions are not additive, meaning if you only set one of the permissions it will only have that permission. So in the case of:

File.chmod(UnixPermissions::USER_READ, awesome_content)

Only read access was available on the file. To set more permissions, you build the permissions using the OR operator (|). So to set the read, write and execute permissions you will need to chain them like so:

These are only a handful of the operations available; there is great documentation up at Ruby-Doc.org. Go ahead and play with some of these methods, sooner or later you are going to need them!

Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.