Created
April 6, 2014 20:47
-
-
Save cheeyeo/10011283 to your computer and use it in GitHub Desktop.
Using ruby tempfile to fetch a remote resource for custom formatting
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
class LocalResource | |
attr_reader :uri | |
def initialize(uri) | |
@uri = uri | |
end | |
def file | |
@file ||= Tempfile.new(tmp_filename, tmp_folder, encoding: encoding).tap do |f| | |
io.rewind | |
f.write(io.read) | |
f.close | |
end | |
end | |
def io | |
@io ||= uri.open | |
end | |
def encoding | |
io.rewind | |
io.read.encoding | |
end | |
def tmp_filename | |
[ | |
Pathname.new(uri.path).basename, | |
Pathname.new(uri.path).extname | |
] | |
end | |
def tmp_folder | |
# If we're using Rails: | |
Rails.root.join('tmp') | |
# Otherwise: | |
# '/wherever/you/want' | |
end | |
end | |
def local_resource_from_url(url) | |
LocalResource.new(URI.parse(url)) | |
end | |
# URL is provided as input | |
url = 'https://s3.amazonaws.com/your-bucket/file.gif' | |
begin | |
# We create a local representation of the remote resource | |
local_resource = local_resource_from_url(url) | |
# We have a copy of the remote file for processing | |
local_copy_of_remote_file = local_resource.file | |
# Do your processing with the local file | |
`some-command-line-utility #{local_copy_of_remote_file.path}` | |
ensure | |
# It's good idea to explicitly close your tempfiles | |
local_copy_of_remote_file.close | |
local_copy_of_remote_file.unlink | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blog post from http://viget.com/extend/make-remote-files-local-with-ruby-tempfile