Skip to content

Instantly share code, notes, and snippets.

@jensendarren
Created January 8, 2015 12:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jensendarren/e78b464a5b21e58faa29 to your computer and use it in GitHub Desktop.
Save jensendarren/e78b464a5b21e58faa29 to your computer and use it in GitHub Desktop.
An example of using FileUtils in Ruby
require 'fileutils'
# __FILE__ keyword in ruby
puts "The current ruby file being executed is #{__FILE__}"
# Gets the directory name of the file being executed
current_directory = File.dirname(__FILE__)
puts "The current directory is #{current_directory}"
# expands to reveal the pwd (Present working directory)
pwd = File.expand_path(current_directory)
puts "The present working directory (using FileUtils.expand_path) is: #{pwd}"
# An easier way is to use the pwd command
pwd = FileUtils.pwd
puts "The present working directory (using FileUtils.pwd) is #{pwd}"
# Lists the directories in the pwd
contents = Dir.entries(pwd)
puts "contents in pwd are #{contents}"
# Make a new directory
FileUtils.mkdir_p(pwd + '/stuff')
# Confirm that it has been created
contents = Dir.entries(pwd)
puts "contents in pwd are now #{contents}"
# Creates (or updates the timestamp) of a file
FileUtils.touch 'file1'
# Copies a file
FileUtils.cp 'file1', 'file2'
# Compares two files
same_files = FileUtils.compare_file('file1', 'file2')
puts "Are they the same files? #{same_files}"
# Its possible to use the FileUtils module without actually making changes to the file sysstem by passing :noop flag
FileUtils.touch('this-should-not-be-created', :noop => true)
puts "This file exists? #{File.exists?('this-should-not-be-created')}"
# If you want to try a bunch of things using FileUtils but not have it affect the file system then use the FileUtils::DryRun module
# This is the same as passing :noop => true as option parameters
FileUtils::DryRun.touch('this-should-not-be-created')
# If you want lots of feedback then pass :verbose => true as option params
FileUtils.touch 'file1', :verbose => true #=> outputs 'touch file1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment