What a safe and easy way to delete a dir in Ruby? - ruby

I'd like to delete a directory that may or may not contain files or other directories. Looking in the Ruby docs I found Dir.rmdir but it won't delete non-empty dir. Is there a convenience method that let's me do this? Or do I need to write a recursive method to examine everything below the directory?

require 'fileutils'
FileUtils.rm_rf(dir)

A pure Ruby way:
require 'fileutils'
FileUtils.rm_rf("/directory/to/go")
If you need thread safety: (warning, changes working directory)
FileUtils.rm_rf("directory/to/go", :secure=>true)

If some looking for answer on #ferventcoder comment -
Just a note, I found that with Windows and Ruby 1.9.3 (at least) FileUtils.rm_rf will follow links (symlinks in this case) and delete those files and folders as well. This was found based on creating a symlink with CreateSymbolicLinkW and then running FileUtils.rm_rf against a parent directory the symlinks are in. Not exactly expected behavior.
– ferventcoder
Safest way is to iterate path and delete it manually.
def rec_del(path):
if path is file call FileUtils.rm_rf - it is safe to delete even in windows
if dir call Dir.rmdir which will succeed for empty dir and dir symlink. else will get ENOTEMPTY for regular non empty dir.
iterate the dir and call rec_del for each item.
now call again Dir.rmdir which will succeed

The laziest way is:
def delete_all(path)
`rm -rf "#{path}"`
end

Related

How can I create a file on my desktop from a Ruby script?

I'm building a webcrawler and I want it to output to a new file that is timestamped. I've completed what I thought would be the more difficult part but I cannot seem to get it to save to the desktop.
Dir.chdir "~/Desktop"
dirname = "scraper_out"
filename = "#{time}"
Dir.mkdir(dirname) unless File.exists?(dirname)
Dir.chdir(dirname)
File.new(filename, "w")
It errors out on the first line
`chdir': No such file or directory # dir_chdir - ~/Desktop
I've read the documentation on FileUtils, File and cannot seem to find where people change into nested directories from the root.
Edit: I don't think FileUtils understands the ~.
~/ is not recognized by Ruby in this context.
Try:
Dir.chdir ENV['HOME']+"/Desktop"
This might help you
Create a file in a specified directory

Ruby - Search and collect files in all directorys

I'm trying to search for a certain file type within all directories on my unix system using a ruby script. I understand the following code will search all files ending with .pdf within the current directory:
my_pdfs = Dir['*pdf']
As well as:
my_pdfs = Dir.glob('*.pdf').each do |f|
puts f
end
But how about searching all directories and sub-directories for files with the .pdf extension?
Check out the Find module:
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/find/rdoc/Find.html
Using Dir.glob is less than ideal since globbing doesn't handle recursion nearly as well as something like find.
Also if you're on a *nix box try using the find command. Its pretty amazingly useful for one liners.
Maybe something like:
pdfs=Dir['/**/*.pdf']
?
Not using Linux right now, so don't know if that will work. The ** syntax implies recursive listing.

Dir globbing not recursing fully

files = Dir[File.join(path, '**', '*.jpg')].each do |s|
puts s
end
I have a bunch of subfolders within a directory and this snippet seems to go into some of the subdirectories, but skips most of them. How can I make it so that it recurses into all directories?
Also, should I be using Find instead? If so, could someone provide an example that does the same as above, namely finding .jpgs in all subdirectories?
EDIT -
Ok, so apparently when I do it with .JPG (capitalized) it finds all the files. Strange... How can I tell to find either of them?
This may help with different extensions:
files = Dir[File.join(path, '**', '*.{jpg,JPG}')].each do |s|
puts s
end
Obviously you forgot use glob method on Dir like:
Dir.glob(File.join('**','*.jpg'))

How to delete a non-empty directory using the Dir class?

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")
causes this error:
Directory not empty - /usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh
How to delete a directory even when it still contains files?
Is not possible with Dir (except iterating through the directories yourself or using Dir.glob and deleting everything).
You should use
require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"
When you delete a directory with the Dir.delete, it will also search the subdirectories for files.
Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")
If the directory was not empty, it will raise Directory not empty error. For that ruby have FiltUtils.rm_r method which will delete the directory no matter what!
require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"
I use bash directly with the system(*args) command like this:
folder = "~/Downloads/remove/this/non/empty/folder"
system("rm -r #{folder}")
It is not really ruby specific but since bash is simpler in this case I use this frequently to cleanup temporary folders and files. The rm command just removes anything you give it and the -r flag tells it to remove files recursively in case the folder is not empty.

Delete hidden files in Ruby

Does anyone know how to delete all files in a directory with Ruby. My script works well when there are no hidden files but when there are (i.e .svn files) I cannot delete them and Ruby raises the Errno::ENOTEMPTY error.
How do I do that ?
If you specifically want to get rid of your svn files, here's a script that will do it without harming the rest of your files:
require 'fileutils'
directories = Dir.glob(File.join('**','.svn'))
directories.each do |dir|
FileUtils.rm_rf dir
end
Just run the script in your base svn directory and that's all there is to it (if you're on windows with the asp.net hack, just change .svn to _svn).
Regardless, look up Dir.glob; it should help you in your quest.
.svn isn't a file, it's a directory.
Check out remove_dir in FileUtils.
It probably has nothing to do with the fact, that .svn is hidden. The error suggest, that you are trying to delete a non empty directory. You need to delete all files within the directory before you can delete the directory.
Yes, you can delete (hiden) directory using FileUtils.remove_dir path.
I happend to just write a script to delete all the .svn file in the directory recursively. Hope it helps.
#!/usr/bin/ruby
require 'fileutils'
def svnC dir
d = Dir.new(dir)
d.each do |f|
next if f.eql?(".") or f.eql?("..")
#if f is directory , call svnC on it
path = dir + "/" + "#{f}"
if File.stat(path).directory?
if f.eql?(".svn")
FileUtils.remove_dir path
else
svnC path
end
end
end
end
svnC FileUtils.pwd
As #evan said you can do
require 'fileutils'
Dir.glob('**/.svn').each {|dir| FileUtils.rm_rf(dir) }
or you can make it a one liner and just execute it from the command line
ruby -e "require 'fileutils'; Dir.glob('**/.svn').each {|dir| FileUtils.rm_rf(dir) }"

Resources