Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip fetch image directly via url

It's it possible to fetch an image via url using PaperClip ? It's possible with fleximage, but fleximage has no support for Rails3 so I've switched over to paperclip.

At present, I'm fetching the image via curl, saving it on the hdd and load it via image_file of paperclip.

I've found no real solution via google, so hopefully you can help me.

like image 894
ghostrifle Avatar asked Jan 28 '11 15:01

ghostrifle


2 Answers

Yes this is possible and amazingly simple.

In your model:

#we use this to get the image.
require 'rest-open-uri'
Class Model << ActiveRecord::Base
has_attached_file :picture

#Get the picture from a given url.
def picture_from_url(url)
    self.picture = open(url)
end

And then you can do something like this:

#controller
@model.picture_from_url(<Your URL here>)

And because we saved the image with the rest of the object. You can just use this in your views:

<%= image_tag @model.picture.url %>

Hope this helps!

like image 158
Daniël Zwijnenburg Avatar answered Oct 11 '22 13:10

Daniël Zwijnenburg


Does the <modelname>.<attachmentname>.url method not do what you're looking for?

In other words, if your model is called Foo, and you set it to has_attached_file :bar then foo.bar.url should give the url of your image, which you can put into an image_tag or a link_to or whatever you want.

Could you clarify what you mean if that isn't what you're looking for?

like image 29
Andrew Avatar answered Oct 11 '22 14:10

Andrew