Interacting with the File System
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.
user_read = 0400 user_write = 0200 user_execute = 0100 group_read = 0040 group_write = 0020 group_execute = 0010 other_read = 0004 other_write = 0002 other_execute = 0001
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:
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:
File.chmod(UnixPermissions::USER_READ | UnixPermissions::USER_WRITE | UnixPermissions::USER_WRITE, awesome_content)
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!