Class: ZOpen::File

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/zopen.rb

Overview

A possible compressed file.

This class delegates all functions to its underlying IO-like object, which should provide the typical read/write methods. However, many compressed files to not allow random access, so methods like seek might not be available.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, mode = nil) ⇒ File

Constructor



130
131
132
# File 'lib/zopen.rb', line 130

def initialize(filename, mode=nil)
  super(openfile(filename, mode))
end

Class Method Details

.new(filename, mode = nil) {|File| ... } ⇒ File Also known as: open

Open file.

The only two open modes that are guaranteed to be supported are ‘r’ and ‘w’ for reading and writing, respectively.

If a code block is given the block is called with the new file as parameter and the file is closed when the block returns.

Parameters:

  • filename (String)

    the name of the file to be opened

  • mode (String, nil) (defaults to: nil)

    the mode to open the file

Yields:

  • (File)

    this file

Returns:

  • (File)

    the opened file



112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/zopen.rb', line 112

def new(filename, mode = nil)
  file = allocate
  file.send(:initialize, filename, mode)
  if block_given?
    begin
      yield file
    ensure
      file.close
    end
  else
    file
  end
end

.read(filename) ⇒ String

Return the content of a file.

Parameters:

  • filename (String)

    the name of the file

Returns:

  • (String)

    the content of the file



138
139
140
# File 'lib/zopen.rb', line 138

def self.read(filename)
  new(filename, 'r') { |f| return f.read }
end

.write(filename, text) ⇒ Object

Write a string to a file.

Parameters:

  • filename (String)

    the name of the file

  • text (String)

    the string to be written to the file



146
147
148
# File 'lib/zopen.rb', line 146

def self.write(filename, text)
  new(filename, 'w') { |f| f.write text }
end