Created
May 25, 2010 14:43
-
-
Save gshutler/413200 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'fileutils' | |
require 'tmpdir' | |
include FileUtils | |
class TempDirectory | |
def self.scoped(root = TempDirectory.timestamp_directory_name) | |
temp_dir = new(root) | |
yield temp_dir if block_given? | |
temp_dir.destroy! | |
end | |
def initialize(root) | |
@root = root | |
ensure_clean_root | |
end | |
def mkdir(name) | |
directory_path = File.join(@root, name) | |
ensure_directory_exists directory_path | |
end | |
def destroy! | |
puts "wiping temp root '#{@root}'" | |
FileUtils.rm_rf Dir.glob(File.join(@root, "**")) | |
Dir.delete(@root) if File.directory?(@root) | |
end | |
private | |
def self.timestamp_directory_name | |
File.join(Dir.tmpdir, Time.now.to_i.to_s) | |
end | |
def ensure_clean_root | |
destroy! | |
ensure_directory_exists @root | |
end | |
def ensure_directory_exists(directory) | |
puts "ensuring directory exists '#{directory}'" | |
Dir.mkdir(directory) unless File.directory?(directory) | |
directory | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment