rubyzipでzipファイルにストリームデータを追加する


Rubyでzipファイルを扱う場合は、Gem rubyzip を利用します。zipruby など他のGemは更新されていないので、現在は rubyzip 一択のようです。

ファイルシステムを使わずに、S3などから取得したファイルをまとめたzipファイルの作成を rubyzip を使って実装をしたので、その手順についてメモしておきます。

Railsで、zipファイルをダウンロードするところまでのコードになります。
[ruby highlight=”1,6-9″]
require ‘zip’

class ZipController < ApplicationController
def download
t = Tempfile.new("my-temp-filename-#{Time.now}")
Zip::OutputStream.open(t.path) do |z|
z.put_next_entry("images/polyvore1.jpg")
z.print Net::HTTP.get URI.parse(‘http://ak1.polyvoreimg.com/cgi/img-set/cid/114613528/id/yAcS_3ae4xGVrWQvSbYPRA/size/l.jpg’)
end

send_file t.path, :type => ‘application/zip’,
:disposition => ‘attachment’,
:filename => "Images.zip"
t.close
end
end
[/ruby]

TUTORIAL: Zip file downloads with Ruby on Rails 4.0 and Rubyzip
Rubyzip: Export zip file directly to S3 without writing tmpfile to disk?

,