environment/lib/downloader.rb

33 lines
977 B
Ruby
Raw Normal View History

2025-08-11 10:20:07 +02:00
require 'uri'
require 'addressable/uri'
2025-08-11 14:18:59 +02:00
require 'user'
require 'fileutils'
require 'open-uri'
2025-08-11 10:20:07 +02:00
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)
2025-08-11 14:18:59 +02:00
path = File.join(User.cache_path, "downloads", uri.domain, uri.path)
2025-08-11 10:20:07 +02:00
#uri = URI.parse(url)
#file_name = File.basename(uri.path)
2025-08-11 14:18:59 +02:00
# 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|
2025-08-11 17:36:55 +02:00
IO.copy_stream(input, output)
2025-08-11 14:18:59 +02:00
end
end
end
2025-08-11 10:20:07 +02:00
yield path
end
end