Last active
August 29, 2015 14:24
-
-
Save breim/c7ea2b48c0cc1baeef5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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