Skip to content

Instantly share code, notes, and snippets.

@BioNuc
Created January 16, 2013 16:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BioNuc/4548388 to your computer and use it in GitHub Desktop.
Save BioNuc/4548388 to your computer and use it in GitHub Desktop.
Upload image from url using Paperclip
# Basic Code
class Image
has_attached_file :attachment
def attachment_url(url)
require "open-uri"
self.attachment = open(url)
end
end
# If you faced memory leakage, I think it is better to do it this way
class Image
has_attached_file :attachment
def attachment_url(url)
require "open-uri"
f = open(url)
self.attachment = f
f.close
end
end
# This way you are making sure that file is closed after it has been utilized
# This will work great unless an exception was thrown. In this case the file won't be closed so better do that
class Image
has_attached_file :attachment
def attachment_url(url)
begin
require "open-uri"
f = open(url)
self.attachment = f
ensure
f.close if f
end
end
end
# This will work fine but you will find that file names are weird and without extension
# so to fix that just add this extra line
class Image
has_attached_file :attachment
def attachment_url(url)
begin
require "open-uri"
f = open(url)
def f.original_filename ; base_uri.path.split('/').last ; end
self.attachment = f
ensure
f.close if f
end
end
end
# This will force usage of the resource name and extension rather than dummy ones used by OpenURI
# If you expect getting urls with spaces and also with Arabic Characters then add this small modification
class Image
has_attached_file :attachment
def attachment_url(url)
url = URI.encode( CGI.unescape( url ) )
begin
require "open-uri"
f = open(url)
def f.original_filename ; base_uri.path.split('/').last ; end
self.attachment = f
ensure
f.close if f
end
end
end
# 1 last Note, I sometimes need to grab too many images and I don't care about non existing ones so I added this modification
class Image
has_attached_file :attachment
def attachment_url(url)
begin
require "open-uri"
f = open(url)
def f.original_filename ; base_uri.path.split('/').last ; end
self.attachment = f
rescue OpenURI::HTTPError => e
raise(e) unless e.message == "404 Not Found"
ensure
f.close if f
end
end
end
# This will raise the exception again only if the problem was not "404" due to non-existance of the resource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment