You want to make a dated archive of a directory to burn to CD or otherwise store on backup media.
This script copies a directory to a timestamped backup. It reuses the File.versioned_ filename method defined in Recipe 6.14, so you can create multiple backups in the same time period:
require fileutils def backup(from_dir, to_dir, time_format="-%Y%m%d") from_path, from_name = File.split(from_dir) now = Time.now.strftime(time_format) Dir.mkdir(to_dir) unless File.exists? to_dir unless File.directory? to_dir raise ArgumentError, "Not a directory: #{to_dir}" end to = File.versioned_filename(File.join(to_dir, from_name + now)) FileUtils.cp_r(from_dir, to, :preserve=>true) return to end # This method copied from "Backing Up to Versioned Filenames" 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 # Create a dummy directory Dir.mkdir( ecipes) # And back it up. backup( ecipes, /tmp/backup) # => "/tmp/backup/recipes-20061031" backup( ecipes, /tmp/backup) # => "/tmp/backup/recipes-20061031.0" backup( ecipes, /tmp/backup, -%Y%m%d-%H.%M.%S) # => "/tmp/backup/recipes-20061031-20.48.56"
The backup method recursively copies the contents of a directory into another directory, possibly on another filesystem. It uses the time-based scheme you specify along with versioned_filename to uniquely name the destination directory.
As written, the backup method uses a lot of space: every time you call it, it creates an entirely new copy of every file in the source directory. Fortunately, the technique has many variations. Instead of copying the files, you can make a timestamped tarball with the techniques from Recipe 12.10. You can archive the files to another computer with the techniques from Recipe 14.11 (although to save space, you should use the rsync program instead). You could even automatically check your work into a version control system every so often; this works better with text than with binary files.
Strings
Numbers
Date and Time
Arrays
Hashes
Files and Directories
Code Blocks and Iteration
Objects and Classes8
Modules and Namespaces
Reflection and Metaprogramming
XML and HTML
Graphics and Other File Formats
Databases and Persistence
Internet Services
Web Development Ruby on Rails
Web Services and Distributed Programming
Testing, Debugging, Optimizing, and Documenting
Packaging and Distributing Software
Automating Tasks with Rake
Multitasking and Multithreading
User Interface
Extending Ruby with Other Languages
System Administration