environment/lib/downloader.rb

33 lines
No EOL
977 B
Ruby

require 'uri'
require 'addressable/uri'
require 'user'
require 'fileutils'
require 'open-uri'
module Downloader
# use_cache => save in the home and return path to it
# forced => download even if the file exists in the cache, saves to chace if use_cache == true
def self.get(url, use_cache = true, forced = false)
uri = Addressable::URI.parse(url)
path = File.join(User.cache_path, "downloads", uri.domain, uri.path)
#uri = URI.parse(url)
#file_name = File.basename(uri.path)
# Ensure the directory exists
dir = File.dirname(path)
FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
unless File.exist?(path)
puts "File does not exist, downloading..."
URI.open(uri) do |input|
File.open(path, 'wb') do |output|
IO.copy_stream(input, output)
end
end
end
yield path
end
end