Reputation: 548
I have a variable storing the files which should be keep
default['keep']['files'] = ['a.txt', 'b.txt']
And bellow files exist on the server
'a.txt', 'b.txt', 'c.txt', 'd.txt'
I want to delete those file which is not in default['keep']['files'], i.e. c.txt and d.txt
but I am not able to figure out how to get the list of the files to be deleted.
// How should I get the list so that i can loop it?
???.each do |file_name|
directory "Delete #{file_name}" do
path my_folder_path
recursive true
action :delete
end
end
Upvotes: 2
Views: 386
Reputation: 12837
You can just subtract keep array from the file list array which will leave you with an array of file names to delete. e.g.
a1 = ['file1', 'file2']
a2 = ['file1', 'file2', 'file3', 'file4']
a3 = a2 - a1 #results in a3 => ['file3', 'file4']
So you could do something like
files_to_keep = ['a.txt', 'b.txt']
all_files = Dir.entries
files_to_delete = all_files - files_to_keep
files_to_delete.each do |file_name|
if ! Dir.exist? #Check that the file name is not an actual directory
# write your code to delete the file named file_name
end
end
But you might want to sort the arrays first, code is untested but should be fine
Upvotes: 1