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.29 lib/epitools/zopen.rb
epitools-0.5.28 lib/epitools/zopen.rb
epitools-0.5.27 lib/epitools/zopen.rb
epitools-0.5.26 lib/epitools/zopen.rb
epitools-0.5.25 lib/epitools/zopen.rb
epitools-0.5.24 lib/epitools/zopen.rb
epitools-0.5.23 lib/epitools/zopen.rb
epitools-0.5.22 lib/epitools/zopen.rb
epitools-0.5.21 lib/epitools/zopen.rb
epitools-0.5.20 lib/epitools/zopen.rb
epitools-0.5.19 lib/epitools/zopen.rb
epitools-0.5.18 lib/epitools/zopen.rb
epitools-0.5.17 lib/epitools/zopen.rb
epitools-0.5.16 lib/epitools/zopen.rb
epitools-0.5.15 lib/epitools/zopen.rb
epitools-0.5.14 lib/epitools/zopen.rb
epitools-0.5.13 lib/epitools/zopen.rb
epitools-0.5.12 lib/epitools/zopen.rb
epitools-0.5.11 lib/epitools/zopen.rb
epitools-0.5.10 lib/epitools/zopen.rb