Hi,

Am Dienstag, 10. Jul 2007, 13:26:14 +0900 schrieb 12 34:
> Coming from OS X, I'm used to protection to overwriting files. I have
> the need for such protection. Before I write it myself is there a
> standard method for this? I'd like it work like OS X where if a file of
> the same name exists, the file to be copied gets an index number. For
> example, existingFile.txt already is in the dest directory, and a file
> of same name being copied becomes existingFile1.txt.

  class File
    class <<self
      def safe_open name
        i = 0
        n = name
        begin
          f = File.new n, File::CREAT|File::EXCL|File::WRONLY
          yield f
        rescue Errno::EEXIST
          i += 1
          n = "#{name}_#{i}"
          retry
        ensure
          f.close
        end
      end
    end
  end
  
  File.safe_open "some_file" do |f|
    puts "Generated filename is: #{f.path}"
    f.puts some_data
  end


Bertram


-- 
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-scharpf.de