net/httpでZIPファイルを開く

Zip/Rubyには、ProcオブジェクトをZIPのストリームとしてファイルを開くという、無駄な機能があるので、少し活用してみる。

#!/usr/bin/env ruby1.9
require 'net/http'
require 'uri'
require 'enumerator'
require 'zipruby'

class WebEnum
  def initialize(uri)
    @uri = URI.parse(uri)
    @http = Net::HTTP.new(@uri.host, @uri.port)
    @itor = self.to_enum
  end

  def next
    @itor.next
  rescue StopIteration
    nil
  end

  private
  def each
    req = Net::HTTP::Get.new(@uri.path)

    @http.request(req) do |res|
      res.read_body do |str|
        yield(str)
      end
    end
  end
end

we = WebEnum.new('http://ftp.ruby-lang.org/pub/ruby/ruby-1.9.1-p129.zip')
stream = lambda { we.next }

Zip::Archive.open_buffer(stream) do |ar|
  puts ar.map {|f| f.name }.slice(0, 10)
end


~/work$ ./bar.rb
ruby-1.9.1-p129/
ruby-1.9.1-p129/.cvsignore
ruby-1.9.1-p129/.document
ruby-1.9.1-p129/.gdbinit
ruby-1.9.1-p129/.gitignore
ruby-1.9.1-p129/.revision.time
ruby-1.9.1-p129/array.c
ruby-1.9.1-p129/bcc32/
ruby-1.9.1-p129/benchmark/
ruby-1.9.1-p129/benchmark/bm_app_answer.rb