Created
June 25, 2016 16:13
-
-
Save ldlsegovia/cd9532914b2eb440fe764ff1f2109cf6 to your computer and use it in GitHub Desktop.
Simple class to create a tmp local file from a url
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
require 'open-uri' | |
class LocalResource | |
def initialize(_url, _tmp_filename) | |
@uri = URI.parse(_url) | |
@tmp_file_name = File.basename(_tmp_filename, ".*") | |
@tmp_file_ext = File.extname(_tmp_filename) | |
end | |
def file | |
filename = [@tmp_file_name, @tmp_file_ext] | |
@file ||= Tempfile.new(filename, self.class.tmp_dir, encoding: encoding).tap do |f| | |
io.rewind | |
f.write(io.read) | |
f.close | |
end | |
end | |
def file_path | |
file.path | |
end | |
def destroy | |
return unless @file | |
@file.delete | |
@file = nil | |
end | |
def self.destroy_tmp_dir | |
FileUtils.rm_rf(tmp_dir) | |
end | |
private | |
def self.tmp_dir | |
path = Rails.root.join('tmp/local_resources') | |
FileUtils::mkdir_p(path.to_s).first | |
end | |
def encoding | |
io.read.encoding | |
end | |
def io | |
@io ||= @uri.open | |
end | |
end | |
# Usage | |
resource = LocalResource.new("http://lorempixel.com/50/50/", "my-file.png") | |
resource.file_path # to get the file location | |
resource.destroy # to delete after use |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment