Skip to content

Instantly share code, notes, and snippets.

@noma4i
Created January 28, 2013 02:53
Show Gist options
  • Save noma4i/4652669 to your computer and use it in GitHub Desktop.
Save noma4i/4652669 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment