Sha256: d8af84cc59c880165393396734a1dfb97d25f2d23153e0f3cebf2dcf36ca72d6

Contents?: true

Size: 950 Bytes

Versions: 21

Compression:

Stored size: 950 Bytes

Contents

require 'zlib'

#
# A mutation of "open" that lets you read/write gzip files, as well as
# regular files.
#
# (NOTE: gzip detection is purely based on the filename.)
#
# 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 } # reads the contents of the .gz file, then closes the file automatically.
#
def zopen(filename, mode="r")

  file = open(filename, mode)
  
  if filename =~ /\.gz$/
    case mode
    when "r", "rb"
      file = Zlib::GzipReader.new(file) 
    when "w", "wb"
      file = Zlib::GzipWriter.new(file) 
    else
      raise "Unknown mode: #{mode.inspect}. zopen only supports 'r' and 'w'."
    end
  end
  
  if block_given?
    result = yield(file)
    file.close
    result
  else
    file
  end
  
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
epitools-0.4.35 lib/epitools/zopen.rb
epitools-0.4.34 lib/epitools/zopen.rb
epitools-0.4.33 lib/epitools/zopen.rb
epitools-0.4.32 lib/epitools/zopen.rb
epitools-0.4.31 lib/epitools/zopen.rb
epitools-0.4.30 lib/epitools/zopen.rb
epitools-0.4.29 lib/epitools/zopen.rb
epitools-0.4.28 lib/epitools/zopen.rb
epitools-0.4.26 lib/epitools/zopen.rb
epitools-0.4.25 lib/epitools/zopen.rb
epitools-0.4.24 lib/epitools/zopen.rb
epitools-0.4.23 lib/epitools/zopen.rb
epitools-0.4.22 lib/epitools/zopen.rb
epitools-0.4.21 lib/epitools/zopen.rb
epitools-0.4.20 lib/epitools/zopen.rb
epitools-0.4.19 lib/epitools/zopen.rb
epitools-0.4.18 lib/epitools/zopen.rb
epitools-0.4.17 lib/epitools/zopen.rb
epitools-0.4.16 lib/epitools/zopen.rb
epitools-0.4.15 lib/epitools/zopen.rb