Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created April 6, 2014 20:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheeyeo/10011283 to your computer and use it in GitHub Desktop.
Save cheeyeo/10011283 to your computer and use it in GitHub Desktop.
Using ruby tempfile to fetch a remote resource for custom formatting
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
@cheeyeo
Copy link
Author

cheeyeo commented Apr 6, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment