Sha256: 2e197f926a9e941543ccc4e32ceab695dd0aa6b2f4fffd425fc7b2ef1b8d5d31

Contents?: true

Size: 938 Bytes

Versions: 17

Compression:

Stored size: 938 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"
      file = Zlib::GzipReader.new(file) 
    when "w"
      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

17 entries across 17 versions & 1 rubygems

Version Path
epitools-0.4.13 lib/epitools/zopen.rb
epitools-0.4.10 lib/epitools/zopen.rb
epitools-0.4.9 lib/epitools/zopen.rb
epitools-0.4.8 lib/epitools/zopen.rb
epitools-0.4.7 lib/epitools/zopen.rb
epitools-0.4.6 lib/epitools/zopen.rb
epitools-0.4.5 lib/epitools/zopen.rb
epitools-0.4.4 lib/epitools/zopen.rb
epitools-0.4.3 lib/epitools/zopen.rb
epitools-0.4.2 lib/epitools/zopen.rb
epitools-0.4.1 lib/epitools/zopen.rb
epitools-0.4.0 lib/epitools/zopen.rb
epitools-0.3.4 lib/epitools/zopen.rb
epitools-0.3.3 lib/epitools/zopen.rb
epitools-0.3.2 lib/epitools/zopen.rb
epitools-0.3.1 lib/epitools/zopen.rb
epitools-0.3.0 lib/epitools/zopen.rb