Class: AIPP::Downloader::HTTP

Inherits:
File
  • Object
show all
Defined in:
lib/aipp/downloader/http.rb

Overview

Remote file via HTTP

Constant Summary collapse

ARCHIVE_MIME_TYPES =
{
  'application/zip' => :zip,
  'application/x-zip-compressed' => :zip
}.freeze

Instance Attribute Summary

Attributes inherited from File

#file

Instance Method Summary collapse

Methods inherited from File

#fetched_file

Constructor Details

#initialize(archive: nil, file:, type: nil, headers: {}) ⇒ HTTP

Returns a new instance of HTTP.



11
12
13
14
15
# File 'lib/aipp/downloader/http.rb', line 11

def initialize(archive: nil, file:, type: nil, headers: {})
  @archive = URI(archive) if archive
  @file, @type, @headers = URI(file), type&.to_s, headers
  @digest = (archive || file).to_digest
end

Instance Method Details

#fetch_to(path) ⇒ File

Returns fetched file.

Parameters:

  • path (Pathname)

    directory where to write the fetched file

Returns:

  • (File)

    fetched file



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/aipp/downloader/http.rb', line 19

def fetch_to(path)
  response = Excon.get((@archive || file).to_s, headers: @headers)
  fail NotFoundError if response.status == 404
  mime_type = ARCHIVE_MIME_TYPES.fetch(response.headers['Content-Type'], :dat)
  downloaded_file = path.join([@digest, mime_type].join('.'))
  ::File.write(downloaded_file, response.body)
  path.join(fetched_file).tap do |target|
    if @archive
      extract(file, from: downloaded_file, as: target)
      ::File.delete(downloaded_file)
    else
      ::File.rename(downloaded_file, target)
    end
  end
  self
end