thoughtbot/paperclip — pull request #624 by Overbryd (2011-10-18 12:18:36+00:00)
Title: Access the uploaded file beyond the paperclip lifecycle

Hy,

I'm reopening #445 with this slightly improved pull request.

@yawn introduced Attachment#uploaded_file in order to access the file that was used to set the attachment via assignment. I've just updated the fork to the latest version of Paperclip and I've added a test that ensures the assignment takes place.

The whole idea is to access the uploaded file conveniently from within the model. This allows for cleaning up files that should not stay within the tmp.

So we can address very specific cleanup issues like this one:

An asynchronous background job bursts a PDF into a file each page. For each file we create a Page record with the pdf as a Paperclip attachment.
Now we have the problem, that all the bursted PDF files stay within the tmp directory until the OS cleans them up. This is especially a problem in environments where we don't have access to those clean up configurations. In our case the tmp directory would quickly fill up, and the server was configured to clean on reboot.

With this small addition we can conveniently clean up those files at the right time.

```ruby
class Page < ActiveRecord::Base

belongs_to :booklet
has_attached_file :pdf
after_save :cleanup_tmpfile

protected

def cleanup_tmpfile
if pdf.uploaded_file && pdf.uploaded_file.path.starts_with?(Dir.tmpdir)
File.unlink(pdf.uploaded_file.path)
end
end
```

```ruby
class Booklet < ActiveRecord::Base
has_many :pages

def create_pages
Dir.glob(File.join(burst_directory, '*.pdf') do |path|
pages.create :pdf => File.open(path)
end
end
end
```

Cheers,

Lukas on behalf of Kreuzwerker