On Jul 1, 1:00 am, 12 34 <rubyfo...@web.knobby.ws> wrote:
> I want to see if any element of an array is equal to a file extension
>
> Something like
>
> require 'find'
> require 'FileUtils'
> src="/folder/on/drive/which/contains/other/folder/and/files"
> dest ='another place'
> extNot2move = %{jpg,JPG,pdf,PDF,MRW}
> Find.find(src) do |fn|
> if File.file?(fn)
> if extNot2Move.{any of the elements} == File.extname(fn) ## this is
> the test I'm interested in
> FileUtils.Move(src, dest)
> end
> end
>
In general, any sort of file operation on a number of files is better
done in a single atomic operation. The reason is that this then makes
it easy to 'undo' the operation in case of failure or in case the user
stops it midway (like with ctrl-c).
A couple of other issues in your code:
- require 'FileUtils' should be 'fileutils'. Your code will be
unportable otherwise.
- FileUtils.Move() does not exist. Use FileUtils.mv or
FileUtils.move.
require 'find'
require 'fileutils'
@files = []
@src = '/folder/on/drive/which/contains/other/folder/and/files'
@dst = 'otherplace'
EXTS = %w( jpg pdf mrw ) # %w() creates array avoiding having to
use , or quotes
#
# Collect the files
#
Find.find(@src) do |elem|
next unless File.file?(elem)
if EXTS.include?( File.extname(elem).downcase )
@files << elem # don't do anything yet, just collect the files
end
end
#
# Simple routine to undo the move
#
def undo_move
@files.each { |f|
src = "#@dst/#{File.basename(f)}"
FileUtils.mv(src, f) if File.exists?(src) and not File.exists?(f)
}
end
#
# Move them
#
trap(INT) { undo_move }
begin
@files.each { |f| FileUtils.mv(f, @dst) }
rescue
undo_move
end
trap(INT) {}