Class: IOP::SFTPFileWriter

Inherits:
Object
  • Object
show all
Includes:
Sink
Defined in:
lib/iop/net/sftp.rb

Overview

Note:

this class depends on external +net-sftp+ gem.

Sink class to write file to SFTP server.

This class an adapter for +Net::SFTP::Session+ class.

Use case: store a number of files filled with random data to remote SFTP server reusing session.

require 'iop/net/sftp'
require 'iop/securerandom'
sftp = Net::SFTP.start('sftp.server', username: 'user',  password: '123')
begin
  (1..3).each do |i|
    ( IOP::SecureRandomGenerator.new(1024) | IOP::SFTPFileWriter.new(sftp, "random#{i}.dat") ).process!
  end
ensure
  sftp.session.close
end

Since:

  • 0.2

Instance Attribute Summary

Attributes included from Sink

#upstream

Instance Method Summary collapse

Constructor Details

#initialize(sftp, file, **options) ⇒ SFTPFileWriter

Creates class instance.

sftp can be either a +String+ of +Net::SFTP::Session+ instance. If it is a string a corresponding +Net::SFTP::Session+ instance will be created with options passed to its constructor.

If sftp is a string, a created SFTP session is managed, e.g. it is closed after the process is complete, otherwise supplied object is left as is and no closing is performed. This allows to reuse SFTP session for a sequence of operations.

Parameters:

  • sftp (String, Net::SFTP::Session)

    SFTP server to connect to

  • file (String)

    file name to process

  • options (Hash)

    extra keyword parameters passed to +Net::SFTP::Session+ constructor

Since:

  • 0.2



145
146
147
148
149
# File 'lib/iop/net/sftp.rb', line 145

def initialize(sftp, file, **options)
  @options = options
  @file = file
  @sftp = sftp
end

Instance Method Details

#process(data = nil) ⇒ Object

Since:

  • 0.2



166
167
168
169
170
171
# File 'lib/iop/net/sftp.rb', line 166

def process(data = nil)
  unless data.nil?
    @sftp.write!(@io, @offset, data)
    @offset += data.size
  end
end

#process!Object

Since:

  • 0.2



151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/iop/net/sftp.rb', line 151

def process!
  setup
  begin
    @io = @sftp.open!(@file, 'w')
    @offset = 0
    begin
      super
    ensure
      @sftp.close(@io)
    end
  ensure
    cleanup
  end
end