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
47 def open_file(filename, options = {}, mode = 'r', &block)
48   mode = options.fetch(:mode, mode); writing = mode =~ /w/
49 
50   encoding = options.fetch(:encoding, ::Encoding.default_external)
51 
52   case filename
53     when '-'
54       io = writing ? $stdout : $stdin
55       io.binmode if mode =~ /b/
56       io.set_encoding(encoding)
57 
58       block ? block[io] : io
59     when /\.gz(?:ip)?\z/i
60       require 'zlib'
61 
62       klass = writing ? ::Zlib::GzipWriter : ::Zlib::GzipReader
63       klass.open(filename, encoding: encoding, &block)
64     else
65       open(filename, mode, encoding: encoding, &block)
66   end
67 end