Forum: Ruby Partial Read From URL

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bbc4b3fca1ae3161257a8636145b424d?d=identicon&s=25 Elliot Temple (curi)
on 2008-11-07 00:26
Can anyone see a problem with this code to read only 20k from a URL? The
http connection will get closed, right?

Is there a better way to do this? My goal is to download the start of
mp3 files and then estimate their duration without downloading the
entire file.

def partial_uri_read(uri)
  u = URI.parse(uri)
  s = ""
  Net::HTTP.start(u.host, u.port) do |http|
    http.request_get(u.path) do |response|
      response.read_body do |chunk|
        s << chunk
        return s if s.size > 20000
      end
    end
  end
  s
end

Thanks
Elliot Temple
1bac2e65d64faf472cf2ebc94f0f5ee0?d=identicon&s=25 Ara Howard (ahoward)
on 2008-11-07 00:34
(Received via mailing list)
On Nov 6, 2008, at 4:24 PM, Elliot Temple wrote:

>  s = ""
>
> Thanks
> Elliot Temple
> --
> Posted via http://www.ruby-forum.


maybe try


require 'open-uri'

uri = ......

open(uri){|fd| fd.read 20000}




a @ http://codeforpeople.com/
Bbc4b3fca1ae3161257a8636145b424d?d=identicon&s=25 Elliot Temple (curi)
on 2008-11-07 00:36
Ara Howard wrote:
> On Nov 6, 2008, at 4:24 PM, Elliot Temple wrote:
>
>>  s = ""
>>
>> Thanks
>> Elliot Temple
>> --
>> Posted via http://www.ruby-forum.
>
>
> maybe try
>
>
> require 'open-uri'
>
> uri = ......
>
> open(uri){|fd| fd.read 20000}

I did try that, but it downloads the entire file in my tests. I tried it
on a large file and it takes minutes to return, whereas my code returns
in a couple seconds. Am I missing something?

> ruby -v
ruby 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0]

Elliot
5316d692cc603c3ad2df0f03869bb96b?d=identicon&s=25 Michael Morin (Guest)
on 2008-11-07 04:34
(Received via mailing list)
Elliot Temple wrote:
>   Net::HTTP.start(u.host, u.port) do |http|
> Thanks
> Elliot Temple

You can try using the Range header in HTTP.  Not all servers have it
enabled I think (or that's what 3 minutes playing with telnet tells me).
  Using range you can define which bytes of the file you want to
download, so the whole file is not downloaded.  You can use this to
download the header and use the length of the file to estimate its
length.
This topic is locked and can not be replied to.