Class: Mechanize

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

Instance Method Summary collapse

Instance Method Details

#download(url, file) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mechanize-downloader.rb', line 17

def download(url,file)
  url = URI.parse(url)
  cli = HTTPClient.new
  @cookie_jar.cookies(url).each do |cookie|
    cli.cookie_manager.parse(cookie.to_s,url)
  end
  
  length = 0;total = 0
  while true
    res = cli.head(url)
    break unless res.status == 302 # HTTP::HTTPFound
    url = URI.parse(res.header["Location"].to_s)
  end

  total = cli.head(url).header["Content-Length"].to_s.to_i
  t = Thread.new {
    conn = cli.get_async(url)
    io = conn.pop.content

    f = file
    f = ::File::open(file, "wb") unless file.is_a?(IO) or file.is_a?(Tempfile)
    while str = io.read(40)
      f.write str
      length += str.length
    end
    f.close unless (file.is_a?(IO) or file.is_a?(Tempfile))
  }

  pbar = ProgressBar.new("Loading",total)
  while  total > length
    sleep 1
    pbar.set(length)
  end
  pbar.finish
  t.join
end