Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip: Assign an image programmatically and set its name

Using Paperclip, I want to grab an image from a URL like this:

require 'open-uri'

user.photo = open(url)

The problem is that I then wind up with a filename like 'open-uri20110915-4852-1o7k5uw'. Is there any way I can change the filename on user.photo?

As an added twist, Paperclip is storing my files on S3, so it'd be even better if I could set the filename I want in the initial assignment, so images get uploaded to the right S3 key. Something like this:

user.photo = open(url), :filename => URI.parse(url).path
like image 739
Paul A Jungwirth Avatar asked Sep 15 '11 18:09

Paul A Jungwirth


2 Answers

You can write the filename back to your instance via:

 photo.instance_write(:file_name, new_file_name)

So if your source URL is like:

 http://example.com/foo.jpg

You can first parse the name from the URL (to get foo.jpg) and then write it back to the instance using the above instance_write method.

like image 99
Cody Caughlan Avatar answered Sep 25 '22 05:09

Cody Caughlan


io = open(url)
def io.original_filename; base_uri.path.split('/').last; end

This will set the filename to the filename in the url.

like image 37
lafeber Avatar answered Sep 22 '22 05:09

lafeber