Sha256: 0cf26311556933b305d9b2ec0ca1e87b5cd670a15f1b6430e1d6331c47ae09b9

Contents?: true

Size: 1.12 KB

Versions: 23

Compression:

Stored size: 1.12 KB

Contents

require 'zlib'

COMPRESSORS = {
  ".gz"  => "gzip",
  ".xz"  => "xz",
  ".bz2" => "bzip2"
}

#
# A mutation of "open" that lets you read/write gzip files, as well as
# regular files.
#
# (NOTE: gzip detection is based on the filename, not the contents.)
#
# It accepts a block just like open()!
#
# Example:
#    zopen("test.txt")          #=> #<File:test.txt>
#    zopen("test.txt.gz")       #=> #<Zlib::GzipReader:0xb6c79424>
#    zopen("otherfile.gz", "w") #=> #<Zlib::GzipWriter:0x7fe30448>>
#    zopen("test.txt.gz") { |f| f.read } # read the contents of the .gz file, then close the file handle automatically.
#
def zopen(path, mode="rb")
  ext = File.extname(path).downcase

  if ext == ".gz"
    io = open(path, mode)
    case mode
    when "r", "rb"
      io = Zlib::GzipReader.new(io)
    when "w", "wb"
      io = Zlib::GzipWriter.new(io)
    else
      raise "Unknown mode: #{mode.inspect}. zopen only supports 'r' and 'w'."
    end
  elsif bin = COMPRESSORS[ext]
    io = IO.popen([bin, "-d" ,"-c", path])
  else
    io = open(path)
  end
  
  if block_given?
    result = yield(io)
    io.close
    result
  else
    io
  end
  
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
epitools-0.5.103 lib/epitools/zopen.rb
epitools-0.5.100 lib/epitools/zopen.rb
epitools-0.5.99 lib/epitools/zopen.rb
epitools-0.5.98 lib/epitools/zopen.rb
epitools-0.5.97 lib/epitools/zopen.rb
epitools-0.5.96 lib/epitools/zopen.rb
epitools-0.5.95 lib/epitools/zopen.rb
epitools-0.5.94 lib/epitools/zopen.rb
epitools-0.5.93 lib/epitools/zopen.rb
epitools-0.5.92 lib/epitools/zopen.rb
epitools-0.5.91 lib/epitools/zopen.rb
epitools-0.5.90 lib/epitools/zopen.rb
epitools-0.5.89 lib/epitools/zopen.rb
epitools-0.5.88 lib/epitools/zopen.rb
epitools-0.5.87 lib/epitools/zopen.rb
epitools-0.5.86 lib/epitools/zopen.rb
epitools-0.5.85 lib/epitools/zopen.rb
epitools-0.5.84 lib/epitools/zopen.rb
epitools-0.5.83 lib/epitools/zopen.rb
epitools-0.5.82 lib/epitools/zopen.rb