Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the standard/correct way to open a paperclip attachment from within Ruby?

Paperclip provides a .url method for getting the URL of an attachment for inclusion in a view.

I need to actually open an attachment as a file from within Ruby.

About six months ago, the latest revision of Paperclip allowed us to call to_file on the attachment object. Although it was undocumented, it worked consistently. But at some point it stopped working.

I want to be able to open the file itself from within a validator (in which case it has not yet been saved to its final location) or from an entirely other method after the ActiveModel object has been saved (in which case the file has been moved to its final location, which might be on Amazon S3).

It seems like the options are:

file = File.new(object.attachment.path)

... which only works with local files, not those on S3. Or:

file = object.attachment.queued_for_write[:original]

... which only works before the first save (I think)?

It seems like there should be an easy way to just open the file (which, in the case of something like Amazon S3, might involve copying it to a temp location) and I'm guessing the answer has something to do with the io_adapters, but I've read through the code (and quite a few StackOverflow questions) and I'm still stumped.

Is there a standard way to open a paperclip attachment as a file that works in all cases?

like image 369
Francis Potter Avatar asked Oct 03 '12 00:10

Francis Potter


1 Answers

This will get you the file (assuming yourmodel attaches a file

require 'open-uri'

file = open(yourmodel.file.url)
like image 110
Jesse Wolgamott Avatar answered Oct 05 '22 22:10

Jesse Wolgamott