Class: IOP::FileWriter

Inherits:
IOWriter show all
Defined in:
lib/iop/file.rb

Overview

Sink class to write received upstream data to a local file.

Contrary to IOWriter, this class manages underlying +IO+ instance in order to close it when the process is finished even if exception is risen.

Use case: generate 1024 bytes of random data and write it to file.

require 'iop/file'
require 'iop/securerandom'
( IOP::SecureRandomGenerator.new(1024) | IOP::FileWriter.new('random.dat') ).process!

Since:

  • 0.1

Instance Attribute Summary

Attributes included from Sink

#upstream

Instance Method Summary collapse

Methods inherited from IOWriter

#process

Methods included from Sink

#process

Constructor Details

#initialize(file, mode: 'wb') ⇒ FileWriter

Creates class instance.

Parameters:

  • file (String)

    name of file to write to

  • mode (String) (defaults to: 'wb')

    open mode for the file; refer to File for details

Since:

  • 0.1



149
150
151
152
153
# File 'lib/iop/file.rb', line 149

def initialize(file, mode: 'wb')
  super(nil)
  @file = file
  @mode = mode
end

Instance Method Details

#process!Object

Since:

  • 0.1



155
156
157
158
159
160
161
162
# File 'lib/iop/file.rb', line 155

def process!
  @io = File.new(@file, @mode)
  begin
    super
  ensure
    @io.close
  end
end