As long as you are using Paperclip 3.1.4 or higher it should be as simple as setting up paperclip on your model:
class Problem
has_attached_file :image
end
And then assigning and saving:
def attach_picture_from_url(url)
@problem.image = URI.parse(url)
@problem.save!
end
With Paperclip 4 there are validations in place to ensure that someone doesn't spoof the content type. If the url that you are fetching is missing the correct extension (e.g. http://exmample.com/foo
returns your jpeg) then you will receive an error about the extension not matching the detected content type. If this is a use-case for you then you can do something like this:
require 'open-uri'
def attach_picture_from_url(url)
image_handle = open url
raise "Not an image" unless image_handle.content_type.start_with? 'image/'
extension = image_handle.content_type.gsub 'image/', ''
temp_file = Tempfile.new ['image', extension]
temp_file.write image_handle.read
temp_file.close
@problem.image = temp_file
@problem_image.save!
ensure
temp_file.unlink if temp_file
end
Obviously this is more complicated, but it will ensure that the file will always have an extension that matches the content type.