Module: Kar::URITask::Util

Included in:
Kar::URITask
Defined in:
lib/kar/uritask.rb

Class Method Summary collapse

Class Method Details

.fetch_http(uri, to, headers = {}) ⇒ String?

TODO:

Consider return value type

Parameters:

  • uri (URI)

    URI to fetch content

  • to (String)

    File path to save content

  • headers (Hash<String, Object?>) (defaults to: {})

    HTTP headers

Returns:

  • (String)

    File path content saved, same to to

  • (nil)

    if remote file responded with 304 Not Modified



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/kar/uritask.rb', line 21

def fetch_http(uri, to, headers = {})
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.start do |http|
    File.open to, "wb" do |file|
      http.request_get uri, headers do |response|
        return if response.kind_of? Net::HTTPNotModified

        response.read_body do |chunk|
          file.write chunk
        end
        begin
          File.utime Time.now, Time.httpdate(response["Last-Modified"]), to
        rescue => err
          warn err
        end
      end
    end
  end
  to
end