Module: Nuggets::File::OpenFileMixin
- Included in:
- File
- Defined in:
- lib/nuggets/file/open_file_mixin.rb
Instance Method Summary collapse
-
#open_file(filename, options = {}, mode = 'r', &block) ⇒ Object
call-seq: File.open_file(filename[, options[, mode]]) -> anIO File.open_file(filename[, options[, mode]]) { |io| … } => anObject.
Instance Method Details
#open_file(filename, options = {}, mode = 'r', &block) ⇒ Object
call-seq:
File.open_file(filename[, options[, mode]]) -> anIO
File.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.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/nuggets/file/open_file_mixin.rb', line 47 def open_file(filename, = {}, mode = 'r', &block) mode = .fetch(:mode, mode); writing = mode =~ /w/ encoding = .fetch(:encoding, ::Encoding.default_external) case filename when '-' io = writing ? $stdout : $stdin io.binmode if mode =~ /b/ io.set_encoding(encoding) block ? block[io] : io when /\.gz(?:ip)?\z/i require 'zlib' klass = writing ? ::Zlib::GzipWriter : ::Zlib::GzipReader klass.open(filename, encoding: encoding, &block) else open(filename, mode, encoding: encoding, &block) end end |