-
-
Save lbvf50mobile/82dfb166cb1b0887b16a0f96ef38a94a to your computer and use it in GitHub Desktop.
An example of using FileUtils in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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