Sha256: 9d9b107224db1559dbc3b98c04b956d3652b2c656e5f47c12e44885eafd83808

Contents?: true

Size: 1001 Bytes

Versions: 12

Compression:

Stored size: 1001 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="r")

  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

12 entries across 12 versions & 1 rubygems

Version Path
epitools-0.4.49 lib/epitools/zopen.rb
epitools-0.4.48 lib/epitools/zopen.rb
epitools-0.4.47 lib/epitools/zopen.rb
epitools-0.4.46 lib/epitools/zopen.rb
epitools-0.4.45 lib/epitools/zopen.rb
epitools-0.4.44 lib/epitools/zopen.rb
epitools-0.4.43 lib/epitools/zopen.rb
epitools-0.4.42 lib/epitools/zopen.rb
epitools-0.4.41 lib/epitools/zopen.rb
epitools-0.4.40 lib/epitools/zopen.rb
epitools-0.4.39 lib/epitools/zopen.rb
epitools-0.4.38 lib/epitools/zopen.rb