2010/1/20 Adam Akhtar <adamtemporary / gmail.com>:
> Im going to be making and removing lots of directories using ruby and Im
> feeling a bit uneasy about it. One of my fears is that a potential typo
> after refactoring, cutting and pasting etc could cause my program to
> delete innocent and system vital directories.
>
> This creation and deletion code will be spread around my project and not
> just one place which makes it more prone to errors. For instance my
> tests will have to constantly remove any directories created during
> testing.
>
> Am i just being paranoid or do you black belt ruby developers have a few
> tricks to guard yourself from this hazzard?

One thing I do during initial phases is to not execute the destructive
code but rather print it to stdout or stderr so I can see what would
happen.  Another approach would be to copy your directory structure to
some temporary space and see what happens.

DRY is also a practice that helps avoid mistakes if you apply it to
the definition of the thing you temporarily create and then want to
remove.  For example

require 'fileutils'

def temp_dir(name)
  name = name.clone unless name.frozen?
  Dir.mkdir name
  begin
    yield name
  ensure
    FileUtils.rm_rf name
  end
end

Then

temp_dir "/tmp/foo" do |d|
  File.open "#{d}/bar", "w" do |io|
    io.puts "test"
  end
end

... and you do not have to repeat the name of the directory.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/