Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Download remote file with Paperclip gem

View gist:1112841
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
# Scenario 1: remote resource returns a binary file;
# the last part of the uri represents the file name
# e.g. http://someurl.com/artists/jeanlucponty/tracks/elephants-in-love.mp3
class Audio < ActiveRecord::Base
has_attached_file :file
 
def file_from_url(url)
self.file = download_remote_file(url)
end
 
private
def download_remote_file(url)
# OpenURI extends Kernel.open to handle URLs as files
io = open(url)
# overrides Paperclip::Upfile#original_filename;
# we are creating a singleton method on specific object ('io')
def io.original_filename
base_uri.path.split('/').last
end
io.original_filename.blank? ? nil : io
end
end
 
# Scenario 2: remote resource returns a binary file in the response body;
# along with the filename in the response headers, e.g.
# Content-Type: audio/mp3
# Content-Transfer-Encoding: binary
# Content-Disposition: attachment; filename=chopping_broccoli.mp3"
class Audio < ActiveRecord::Base
has_attached_file :file
 
def file_from_url(url)
self.file = download_remote_file(url)
end
 
private
def download_remote_file(url)
# OpenURI extends Kernel.open to handle URLs as files
io = open(url)
# overrides Paperclip::Upfile#original_filename;
# we are creating a singleton method on specific object ('io')
def io.original_filename
# OpenURI::Meta's meta attribute returns a hash of headers
meta["content-disposition"].match(/filename=(.+[^;])/)[1]
end
io.original_filename.blank? ? nil : io
end
end
 
# example usage
audio = Audio.new
audio.content_from_url('http://someurl.com/someresource.mp3')
artist.audios << audio

This was extremely helpful! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.