Class: SFTPWriter::Remote

Inherits:
Object
  • Object
show all
Defined in:
lib/sftp_writer/remote.rb

Instance Method Summary collapse

Constructor Details

#initialize(config, logger:) ⇒ Remote

Returns a new instance of Remote.



5
6
7
8
# File 'lib/sftp_writer/remote.rb', line 5

def initialize(config, logger:)
  @config = config
  @logger = logger
end

Instance Method Details

#closeObject



23
24
25
26
27
28
29
# File 'lib/sftp_writer/remote.rb', line 23

def close
  return unless @sftp && sftp.open?

  @logger.info('Disconnected from SFTP')
  sftp.session.close
  true
end

#sftpObject



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/sftp_writer/remote.rb', line 10

def sftp
  @sftp ||= begin
    key_data = File.read(@config.key_path)
    Net::SFTP.start(
      @config.host,
      @config.user,
      port: @config.port,
      key_data: [key_data]
    )
  end
  @sftp
end

#write(contents, filename) ⇒ Object



41
42
43
44
45
46
# File 'lib/sftp_writer/remote.rb', line 41

def write(contents, filename)
  path = File.join([write_path(filename), sanitize(filename)].compact)
  @logger.info("Writing #{path}")
  mkdir_safe(path)
  sftp.upload!(StringIO.new(contents), path)
end

#write_path(filename) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/sftp_writer/remote.rb', line 31

def write_path(filename)
  if filename.starts_with?('307_')
    @config.relative_307_path || @config.relative_path || nil
  elsif filename.starts_with?('351_')
    @config.relative_351_path || @config.relative_path || nil
  else
    @config.relative_path || nil
  end
end