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.74 lib/epitools/zopen.rb
epitools-0.5.73 lib/epitools/zopen.rb
epitools-0.5.72 lib/epitools/zopen.rb
epitools-0.5.71 lib/epitools/zopen.rb
epitools-0.5.70 lib/epitools/zopen.rb
epitools-0.5.69 lib/epitools/zopen.rb
epitools-0.5.68 lib/epitools/zopen.rb
epitools-0.5.67 lib/epitools/zopen.rb
epitools-0.5.66 lib/epitools/zopen.rb
epitools-0.5.65 lib/epitools/zopen.rb
epitools-0.5.64 lib/epitools/zopen.rb
epitools-0.5.63 lib/epitools/zopen.rb
epitools-0.5.61 lib/epitools/zopen.rb
epitools-0.5.60 lib/epitools/zopen.rb
epitools-0.5.59 lib/epitools/zopen.rb
epitools-0.5.58 lib/epitools/zopen.rb
epitools-0.5.57 lib/epitools/zopen.rb
epitools-0.5.56 lib/epitools/zopen.rb
epitools-0.5.55 lib/epitools/zopen.rb
epitools-0.5.54 lib/epitools/zopen.rb