Class: Dister::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/dister/downloader.rb

Overview

Curl wrapper for downloading appliance builds.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, message) ⇒ Downloader

Returns a new instance of Downloader.

Parameters:

  • url (String)

    URL of file to be downloaded

  • message (String)

    Message to be displayed while downloading



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/dister/downloader.rb', line 9

def initialize url, message
  @filename = File.basename(url)
  @message  = message

  # setup curl
  @curl = Curl::Easy.new
  @curl.url = url
  @curl.follow_location = true

  @curl.on_body { |data| self.on_body(data); data.size }
  @curl.on_complete { |data| self.on_complete }
  @curl.on_failure { |data| self.on_failure }
  @curl.on_progress do |dl_total, dl_now, ul_total, ul_now|
    self.on_progress(dl_now, dl_total, @curl.download_speed, @curl.total_time)
    true
  end
end

Instance Attribute Details

#filename (readonly)

Returns the value of attribute filename.



5
6
7
# File 'lib/dister/downloader.rb', line 5

def filename
  @filename
end

Instance Method Details

#on_body(data)



34
35
36
# File 'lib/dister/downloader.rb', line 34

def on_body(data)
  @file.write(data)
end

#on_complete



44
45
46
47
# File 'lib/dister/downloader.rb', line 44

def on_complete
  @pbar.finish
  @file.close
end

#on_failure



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/dister/downloader.rb', line 49

def on_failure
  begin
    unless code == 'Curl::Err::CurlOKNo error'
      @pbar.finish
      STDOUT.flush
      raise "Download failed with error code: #{code}"
    end
  ensure
    @file.close
  end
end

#on_progress(downloaded_size, total_size, download_speed, downloading_time)



38
39
40
41
42
# File 'lib/dister/downloader.rb', line 38

def on_progress(downloaded_size, total_size, download_speed, downloading_time)
  if total_size > 0
    @pbar.set(downloaded_size / total_size * 100)
  end
end

#start

Starts the download



28
29
30
31
32
# File 'lib/dister/downloader.rb', line 28

def start
  @file = File.open(@filename, "wb")
  @pbar = ProgressBar.new(@message, 100)
  @curl.perform
end