Class: DwcaHunter::Downloader

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_url, file_path) ⇒ Downloader

Returns a new instance of Downloader.



7
8
9
10
11
12
13
# File 'lib/dwca_hunter/downloader.rb', line 7

def initialize(source_url, file_path)
  @source_url = source_url
  @file_path = file_path
  @url = Url.new(source_url)
  @download_length = 0
  @filename = nil
end

Instance Attribute Details

#urlObject (readonly)

Returns the value of attribute url.



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

def url
  @url
end

Instance Method Details

#downloadObject

downloads a given file into a specified filename. If block is given returns download progress



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/dwca_hunter/downloader.rb', line 17

def download
  raise "#{@source_url} is not accessible" unless @url.valid?
  f = open(@file_path,'wb')
  count = 0
  @url.net_http.request_get(@url.path) do |r|
    r.read_body do |s|
      @download_length += s.length
      f.write s
      if block_given?
        count += 1
        if count % 100 == 0
          yield @download_length
        end
      end
    end
  end
  f.close
  downloaded = @download_length
  @download_length = 0
  downloaded
end

#download_with_percentageObject



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dwca_hunter/downloader.rb', line 39

def download_with_percentage
  start_time = Time.now
  download do |r|
    percentage = r.to_f/@url.header.content_length * 100
    elapsed_time = Time.now - start_time
    eta = calculate_eta(percentage, elapsed_time)
    res = { percentage: percentage,
            elapsed_time: elapsed_time,
            eta: eta }
    yield res
  end
end