Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing old data with Rails and Paperclip

I'm using paperclip for attachments in my application. I'm writing an import script for a bunch of old data, but I don't know how to create paperclip objects from files on disk. My first guess is to create mock CGI multipart objects, but that seems like a bit of a crude solution, and my initial attempt failed, I think because I didn't get the to_tempfile method right.

Is there a Right Way to do this? It seems like something that should be fairly easy.

like image 749
Zak Avatar asked Dec 07 '09 23:12

Zak


2 Answers

I know that I've done the same thing, and I believe that I just created a File object from the path to each file, and assigned it to the image attribute. Paperclip will run on that file:

thing.image = File.new("/path/to/file.png")
thing.save
like image 79
Ben Avatar answered Sep 21 '22 12:09

Ben


This works great for local files but it doesn't work as well for remote files. I have an app that uses paperclip for uploading images. Those images are getting stored on amazon s3. Anyway, I had some old data that I needed to import so I tried the following:

thing.image = open('http://www.someurl.com/path/to/image.jpg')
thing.save

If the file is small (say, less than 10K) then openuri returns a stringio object and my file would get stored on s3 as stringio.txt

If the file is larger than around 10K, then openuri returns a TempFile object. But the filename on s3 ends up being unique, but not really relating to the original filename of image.jpg

I was able to fix the problem by doing the following:

remote_photo = open('http://www.someurl.com/path/to/image.jpg')
def remote_photo.original_filename;base_uri.path.split('/').last; end   
thing.image = remote_photo
thing.save
like image 15
Francois Avatar answered Sep 23 '22 12:09

Francois