Aaron Moodie
Aaron Moodie

Reputation: 1965

Converting python script to ruby (downloading part of a file)

I've been at this for a couple of day, and am having no luck at all. Despite reading over these two posts, I can't seem to rewrite this little python script I did up in ruby.

clean_link = link['href'].replace(' ', '%20')
mp3file = urllib2.urlopen(clean_link)
output = open('temp.mp3','wb')
output.write(mp3file.read(2000))
output.close()

I've been looking at using open-uri and net/http to do the same in ruby, but keep hitting a url redirect issue. So far I have

clean_link = link.attributes['href'].gsub(' ', '%20')
link_pieces = clean_link.scan(/http:\/\/(?:www\.)?([^\/]+?)(\/.*?\.mp3)/)

host = link_pieces[0][0]
path = link_pieces[0][1] 

Net::HTTP.start(host) do |http|
    resp = http.get(path)
    open("temp.mp3", "wb") do |file|
        file.write(resp.body)
    end
end

Is there a simpler way to do this in ruby? Also, as with the python script, is there a way to only download part of the file?

EDIT: progress updated

Upvotes: 1

Views: 325

Answers (1)

zed_0xff
zed_0xff

Reputation: 33227

see here & here

http.request_get('/index.html') {|res|
  size = 0
  res.read_body do |chunk|
     size += chunk.size
     # do some processing
     break if size >= 2000
  end
}

but you can't control chunk sizes here

Upvotes: 1

Related Questions