4

I am trying to build a file downloader with the RubyGem Curb. (Look at This Question.)

I am trying to download a zip file and then with the class File I am trying to actually make the file so that I can double click it in Finder (I am on OS X). How would I go about to convert this "Curl'ed" body to a zip-file.

require 'rubygems'
require 'curb'

class Download
  def start
    curl = Curl::Easy.new('http://wordpress.org/latest.zip')
    curl.perform
    curl.on_body {
      |d| f = File.new('test.zip', 'w') {|f| f.write d}
    }
  end
end

dl = Download.new
dl.start

I am not getting any error, neither can I find any file. I have tried absolute paths with no difference.

Community
  • 1
  • 1
maetthew
  • 191
  • 2
  • 14
  • 1
    You're adding the `on_body` event after calling `perform`, which transfers the body. Does the code work if you create that event before calling `curl.perform`? – Jon Gauthier Mar 21 '11 at 20:24
  • Ahh of course I have to call `on_body` before `perform`. I also had to change the File.new parameter `'w'` to `'a'` – maetthew Mar 21 '11 at 20:31
  • Great, glad that fixed it. I'll add this as an answer as well so other people can find the solution easily :) – Jon Gauthier Mar 21 '11 at 20:33
  • @maetthew, could you check-mark the answer as good? – Tim Snowhite Mar 21 '11 at 20:48
  • @Tim Snowwhite @Hans Engel I was just about to ask you to post it as an answer, good you beat me to it :) Checked it as answered – maetthew Mar 21 '11 at 21:24

2 Answers2

4

I am using ruby 2.0

and my code is:

curl = Curl::Easy.new('http://somepage.cz/index.html')
curl.on_body do |d|
  f = File.open('output_file.html', 'w') {|f| f.write(d)}
end
curl.perform

I had to change File.new to File.open without this it didn't worked. Moving curl.perfom on the end does helped me.

2

You're adding the on_body event after calling perform, which transfers the body. If you move the event declaration to before the perform call, this should work.

Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69