class IOP::SFTPFileReader

Feed class to read file from SFTP server.

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

### Use case: retrieve current user's _~/.profile_ file from SFTP server running on local machine and and compute its MD5 hash sum.

require 'iop/digest'
require 'iop/net/sftp'
( IOP::SFTPFileReader.new('localhost', '.profile') | (d = IOP::DigestComputer.new(Digest::MD5.new)) ).process!
puts d.digest.hexdigest

@note this class depends on external net-sftp gem. @since 0.2

Public Class Methods

new(sftp, file, size: nil, offset: nil, block_size: DEFAULT_BLOCK_SIZE, **options) click to toggle source

Creates class instance.

@param sftp [String, Net::SFTP::Session] SFTP server to connect to

@param file [String] file name to process

@param size [Integer] total number of bytes to read; nil value instructs to read until end-of-data is reached

@param offset [Integer] offset in bytes from the stream start to seek to; nil value means no seeking is performed

@param block_size [Integer] size of blocks to process data with

@param options [Hash] extra keyword parameters passed to Net::SFTP::Session constructor, such as username, password etc.

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.

Refer to Net::SFTP documentation for available options.

Calls superclass method IOP::RandomAccessReader::new
# File lib/iop/net/sftp.rb, line 73
def initialize(sftp, file, size: nil, offset: nil, block_size: DEFAULT_BLOCK_SIZE, **options)
  super(size: size, offset: offset, block_size: block_size)
  @options = options
  @file = file
  @sftp = sftp
end

Public Instance Methods

process!() click to toggle source
Calls superclass method IOP::Feed#process!
# File lib/iop/net/sftp.rb, line 80
def process!
  setup
  begin
    @io = @sftp.open!(@file, 'r')
    begin
      super
    ensure
      @sftp.close(@io)
    end
  ensure
    cleanup
  end
end

Private Instance Methods

read!(read_size, buffer) click to toggle source
# File lib/iop/net/sftp.rb, line 96
def read!(read_size, buffer)
  data = @sftp.read!(@io, @offset ||= 0, read_size)
  @offset += data.size unless data.nil?
  data
end