Handling common file operations with FileUtils
The FileUtils module provides a convenient way to perform common file operations in Ruby, such as copying, moving, and deleting files and directories. It is part of Ruby's standard gems, so you don't need to install any additional dependencies to use it.
The design of FileUtils is based on well-known command-line utilities like cp, mv and rm, which makes it intuitive to use for anyone familiar with Unix-like systems:
require "fileutils"
# Copy a file:
FileUtils.cp("source.txt", "destination.txt")
# Move a file:
FileUtils.mv("old_location.txt", "new_location.txt")
# Delete a file:
FileUtils.rm("sacrilegious_file.txt")
# Copy a directory:
FileUtils.cp_r("source_directory", "destination_directory")
# Delete a directory:
FileUtils.rm_rf("worst_directory_ever")
# Change ownership of a file:
FileUtils.chown("new_owner", "new_group", "file.txt")
# Change permissions of a file:
FileUtils.chmod(0644, "file.txt")
# Create a file:
FileUtils.touch("new_file.txt")
# Create a directory:
FileUtils.mkdir("new_directory")
# Create nested directories:
FileUtils.mkdir_p("parent_directory/child_directory")
# Etc...
One approach to using FileUtils is to include it and suddenly your script might look quite a lot like a shell script, but with the full power of Ruby at your disposal:
require "fileutils"
include FileUtils
cp "source.txt", "destination.txt"
mv "old_location.txt", "new_location.txt"
rm "sacrilegious_file.txt"
# Etc...
Some of the methods in FileUtils have similar methods available on File and Dir, but the FileUtils versions often provide additional convenience, such as support for copying directories recursively with cp_r or creating nested directories with mkdir_p.
Very handy!
History
The FileUtils module was introduced in Ruby 1.8, released in 2003.