Skip to content

Instantly share code, notes, and snippets.

@adjohu
Created February 6, 2012 16:23
Show Gist options
  • Save adjohu/1753083 to your computer and use it in GitHub Desktop.
Save adjohu/1753083 to your computer and use it in GitHub Desktop.
def upload(file)
require 'fileutils'
# Get upload path and create it if needed
file_dir = self.user.get_file_dir
FileUtils.mkdir_p(file_dir)
filename = file.original_filename
tmpfile = file.tempfile
# Write the file with a unique filename
loop do
begin
file_path = path(filename)
File.open(file_path, File::CREAT | File::EXCL | File::WRONLY) do |file|
file.write(tmpfile.read)
end
break
rescue Errno::EEXIST
puts "File exists #{filename}"
filename = increment(filename)
redo
end
end
self.filename = filename
self.save
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment