Class: RMD::Downloader

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(link, options = {}) ⇒ Downloader

Returns a new instance of Downloader.



9
10
11
12
# File 'lib/rmd/downloader.rb', line 9

def initialize(link, options = {})
  @link = link
  @options = options
end

Instance Attribute Details

Returns the value of attribute link.



7
8
9
# File 'lib/rmd/downloader.rb', line 7

def link
  @link
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/rmd/downloader.rb', line 7

def options
  @options
end

Class Method Details

.download(link, options = {}) ⇒ Object



42
43
44
# File 'lib/rmd/downloader.rb', line 42

def self.download(link, options = {})
  new(link, options).download
end

Instance Method Details

#downloadObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rmd/downloader.rb', line 14

def download
  puts file_name.green

  progress_bar = ProgressBar.create(
    starting_at: 0,
    total: nil,
    format: "%a %B %p%% %r KB/sec",
    rate_scale: lambda { |rate| rate / 1024 }
  )

  content_length_proc = Proc.new { |content_length|
    progress_bar.total = content_length
  }

  progress_proc = Proc.new { |bytes_transferred|
    if progress_bar.total && progress_bar.total < bytes_transferred
      progress_bar.total = nil
    end
    progress_bar.progress = bytes_transferred
  }

  open(link, "rb", content_length_proc: content_length_proc, progress_proc: progress_proc) do |page|
    File.open(file_path, "wb") do |file|
      file.write(page.read)
    end
  end
end