Class: Evm::RemoteFile

Inherits:
Object
  • Object
show all
Defined in:
lib/evm/remote_file.rb

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ RemoteFile

Returns a new instance of RemoteFile.



8
9
10
# File 'lib/evm/remote_file.rb', line 8

def initialize(url)
  @url = url
end

Instance Method Details

#download(path, &block) ⇒ Object



12
13
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/evm/remote_file.rb', line 12

def download(path, &block)
  return if File.exist?(path)

  file = File.open(path, 'w')

  thread = Thread.new do
    this = Thread.current
    body = this[:body] = []

    request @url do |response|
      length = this[:length] = response['Content-Length'].to_i

      response.read_body do |fragment|
        body << fragment

        this[:done] = (this[:done] || 0) + fragment.length
        this[:progress] = this[:done].quo(length) * 100
      end
    end

    file.write(body.join)
  end

  until thread.join(1)
    yield thread[:progress]
  end

  file.close
end