Sha256: 877e234e70cf2f74c1ac290b80b8ef646e7394580545591f82a59097b137c0e8

Contents?: true

Size: 1004 Bytes

Versions: 70

Compression:

Stored size: 1004 Bytes

Contents

require 'epitools'

#
# 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")
  
  path = Path[path] unless path.is_a? Path
  file = path.open(mode)
  
  if path.ext == "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

70 entries across 70 versions & 1 rubygems

Version Path
epitools-0.5.51 lib/epitools/zopen.rb
epitools-0.5.50 lib/epitools/zopen.rb
epitools-0.5.49 lib/epitools/zopen.rb
epitools-0.5.47 lib/epitools/zopen.rb
epitools-0.5.46 lib/epitools/zopen.rb
epitools-0.5.45 lib/epitools/zopen.rb
epitools-0.5.44 lib/epitools/zopen.rb
epitools-0.5.43 lib/epitools/zopen.rb
epitools-0.5.42 lib/epitools/zopen.rb
epitools-0.5.41 lib/epitools/zopen.rb
epitools-0.5.39 lib/epitools/zopen.rb
epitools-0.5.38 lib/epitools/zopen.rb
epitools-0.5.37 lib/epitools/zopen.rb
epitools-0.5.36 lib/epitools/zopen.rb
epitools-0.5.35 lib/epitools/zopen.rb
epitools-0.5.34 lib/epitools/zopen.rb
epitools-0.5.33 lib/epitools/zopen.rb
epitools-0.5.32 lib/epitools/zopen.rb
epitools-0.5.31 lib/epitools/zopen.rb
epitools-0.5.30 lib/epitools/zopen.rb