これは古いスレッドですが、私の調査によれば、RubyでHTTPを介してファイルの一部のみを読み取る方法の問題は、まだほとんど答えられていません。これが私がNet::HTTPに少しパッチを当てることによって思いついた解決策です:
require 'net/http'
# provide access to the actual socket
class Net::HTTPResponse
attr_reader :socket
end
uri = URI("http://www.example.com/path/to/file")
begin
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new(uri.request_uri)
# calling request with a block prevents body from being read
http.request(request) do |response|
# do whatever limited reading you want to do with the socket
x = response.socket.read(100);
# be sure to call finish before exiting the block
http.finish
end
end
rescue IOError
# ignore
end
レスキューは、HTTP.finishを時期尚早に呼び出したときにスローされるIOErrorをキャッチします。
参考までに、オブジェクト内のソケットは実際のHTTPResponse
オブジェクトではありませんIO
(これはと呼ばれる内部クラスです)が、必要なメソッドBufferedIO
を模倣するためにモンキーパッチを適用するのも非常に簡単です。IO
たとえば、私が使用していた別のライブラリ(exifr)には、readchar
簡単に追加できるメソッドが必要でした。
class Net::BufferedIO
def readchar
read(1)[0].ord
end
end