module Nuggets::File::OpenFileMixin

Public Instance Methods

open_file(filename[, options[, mode]]) → anIO click to toggle source
open_file(filename[, options[, mode]]) { |io| ... } → anObject

Supported options are mode (defaults to r) and encoding (defaults to the default external encoding).

If filename is -, sets io to STDOUT when in write mode or STDIN otherwise. Puts io into binary mode if requested. Sets io's encoding.

If filename ends with .gz or .gzip, uses Zlib for reading or writing the file.

Otherwise defers to ::open.

Yields io to the given block or returns it when no block given.

# File lib/nuggets/file/open_file_mixin.rb, line 47
def open_file(filename, options = {}, mode = 'r', &block)
  mode = options.fetch(:mode, mode); writing = mode =~ /w/

  encoding = options.fetch(:encoding, ::Encoding.default_external)

  case filename
    when '-'
      io = writing ? $stdout : $stdin
      io.binmode if mode =~ /b/

      block ? block[io] : io
    when /\.gz(?:ip)?\z/i
      require 'zlib'

      klass = writing ? ::Zlib::GzipWriter : ::Zlib::GzipReader, encoding: encoding, &block)
      open(filename, mode, encoding: encoding, &block)