ziprubyを使ってみた

環境

OS CentOS release 5.3 (Final)
ruby ruby 1.8.6 (2010-02-05 patchlevel 399) [i686-linux]
zipruby 0.3.6

ziprubyのinstall

% wget http://rubyforge.org/frs/download.php/68803/zipruby-0.3.6.gem
% sudo gem install --no-rdoc -l zipruby-0.3.6.gem

確認

% gem list zipruby
*** LOCAL GEMS ***

zipruby (0.3.6)
    Ruby bindings for libzip.

サンプルファイルについて

hoge.zip を使います。hoge.zip を解凍すると、以下の3つのファイルになります。

  • hoge.html
  • 1.jpg
  • 2.gif

それぞれの中身は以下です。

<html>
  <head>
    <title>サンプルHTML</title>
  </head>
  <body>
    <h1>ほげほげ</h1>
    <div><img src="1.gif"></div>
    <div><img src="2.jpg"></div>
   </body>
</html>
  • 1.jpg

  • 2.gif


irbで使ってみる

% irb -rubygems

require 'zipruby'
=> true

# ファイル数取得
Zip::Archive.open('/tmp/hoge.zip') do |archive|
  archive.num_files
end
=> 3

# ファイルリスト
Zip::Archive.open('/tmp/hoge.zip') do |archive|
  archive.num_files.times do |i|
      p archive.get_name(i)
  end
end
"1.jpg"
"2.gif"
"hoge.html"
=> 3

# ファイルサイズの取得
Zip::Archive.open('/tmp/hoge.zip') do |archive|
  archive.num_files.times do |i|
   entry_name = archive.get_name(i)

   archive.fopen(entry_name) do |f| 
    puts f.name, f.size, f.comp_size
   end
  end
end
1.jpg
9937
9068
2.gif
15031
14275
hoge.html
175
120
=> 3

# ファイルの実体を取得
Zip::Archive.open('/tmp/hoge.zip') do |archive|
 archive.num_files.times do |i|
  entry_name = archive.get_name(i)

  archive.fopen(entry_name) do |f| 
   puts f.read
  end
 end
end

# 名前を配列で取得
Zip::Archive.open('/tmp/hoge.zip') do |archive|
 entry_names = archive.map { |f| f.name }
end
=> ["1.jpg", "2.gif", "hoge.html"]

解凍だけでなく、zip圧縮等できます。詳しくは、http://zipruby.rubyforge.org/ を御覧ください。