6.14备份至带版本号的文件名。
Problem
You want to copy a file to a numbered backup before overwriting the original file. More generally: rather than overwriting an existing file, you want to use a new file whose name is based on the original filename.
Solution
Use String#succ to generate versioned suffixes for a filename until you find one that doesn't already exist:
class File
def File.versioned_filename(base, first_suffix='.0')
suffix = nil
filename = base
while File.exists?(filename)
suffix = (suffix ? suffix.succ : first_suffix)
filename = base + suffix
end
return filename
end
end
5.times do |i|
name = File.versioned_filename('filename.txt')
open(name, 'w') { |f| f << "Contents for run #{i}" }
puts "Created #{name}"
end
# Created filename.txt
# Created filename.txt.0
# Created filename.txt.1
# Created filename.txt.2
# Created filename.txt.3
If you want to copy or move the original file to the versioned filename as a prelude to writing to the original file, include the ftools library to add the class methods File. copy and File.move. Then call versioned_filename and use File.copy or File.move to put the old file in its new place:
require 'ftools'
class File
def File.to_backup(filename, move=false)
new_filename = nil
if File.exists? filename
new_filename = File.
versioned_filename(filename)
File.send(move ? :move : :copy, filename, new_filename)
end
return new_filename
end
end
Let's back up filename.txt a couple of times. Recall from earlier that the files filename.txt.[0-3] already exist.
File.to_backup('filename.txt') # => "filename.txt.4"
File.to_backup('filename.txt') # => "filename.txt.5"
Now let's do a destructive backup:
File.to_backup('filename.txt', true) # => "filename.txt.6"
File.exists? 'filename.txt' # => false
#You can't back up what doesn't exist:
File.to_backup('filename.txt') # => nil