class StupidDownloader::HTTPDownloader
Attributes
directory[R]
file_name[RW]
url[R]
Public Class Methods
new(**options)
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 10 def initialize **options options.each { |key, value| send "#{ key }=", value } self.directory ||= File.join %w[ private downloads ] end
Public Instance Methods
directory=(value)
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 16 def directory= value @directory = value FileUtils.mkdir_p directory value end
download!()
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 22 def download! fail 'file_name is required' unless file_name File.open file_path, 'w+' do |file| Net::HTTP.start(uri.hostname, uri.port) { |http| download http, to: file } end end
etag()
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 30 def etag @etag ||= File.exists?(etag_path) ? open(etag_path).read : nil end
uri()
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 34 def uri @uri ||= URI.parse url end
url=(value)
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 38 def url= value @url = value @file_name ||= File.basename value rescue nil value end
Private Instance Methods
download(http, **options)
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 46 def download http, **options file = options.fetch :to http.request request do |response| if response.code == '200' record_etag response['etag'] response.read_body { |chunk| file.write chunk } else fail response.inspect unless response.code == '304' end return response end end
etag_path()
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 61 def etag_path @etag_path ||= Pathname.new File.join directory, "#{ file_name }.etag" end
file_path()
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 65 def file_path @file_path ||= Pathname.new File.join directory, file_name end
record_etag(etag)
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 69 def record_etag etag File.open(etag_path, 'w+') { |f| f.write etag } end
request(force = false)
click to toggle source
# File lib/stupid_downloader/http_downloader.rb, line 73 def request force = false @request ||= Net::HTTP::Get.new uri @request['If-None-Match'] = etag if etag @request end