Class: Remi::Extractor::SftpFile

Inherits:
Object
  • Object
show all
Defined in:
lib/remi/extractor/sftp_file.rb

Defined Under Namespace

Classes: FileNotFoundError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(credentials:, remote_file:, remote_folder: '', local_folder: Settings.work_dir, port: '22', most_recent_only: false, logger: Remi::Settings.logger) ⇒ SftpFile

Returns a new instance of SftpFile.



18
19
20
21
22
23
24
25
26
# File 'lib/remi/extractor/sftp_file.rb', line 18

def initialize(credentials:, remote_file:, remote_folder: '', local_folder: Settings.work_dir, port: '22', most_recent_only: false, logger: Remi::Settings.logger)
  @credentials = credentials
  @remote_file = remote_file
  @remote_folder = remote_folder
  @local_folder = local_folder
  @port = port
  @most_recent_only = most_recent_only
  @logger = logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



28
29
30
# File 'lib/remi/extractor/sftp_file.rb', line 28

def logger
  @logger
end

Instance Method Details

#all_entries(remote_folder = @remote_folder) ⇒ Object



36
37
38
# File 'lib/remi/extractor/sftp_file.rb', line 36

def all_entries(remote_folder = @remote_folder)
  @all_entries ||= connection { |sftp| sftp.dir.entries(File.join("/", remote_folder)) }
end

#download(to_download = matching_entries, local_folder: @local_folder, ntry: 3) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/remi/extractor/sftp_file.rb', line 48

def download(to_download = matching_entries, local_folder: @local_folder, ntry: 3)
  connection do |sftp|
    to_download.map do |entry|
      local_file = File.join(local_folder, entry.name)
      @logger.info "Downloading #{entry.name} to #{local_file}"
      retry_download(ntry) { sftp.download!(entry.name, local_file) }
      local_file
    end
  end
end

#extractObject

Raises:



30
31
32
33
34
# File 'lib/remi/extractor/sftp_file.rb', line 30

def extract
  to_download = @most_recent_only ? Array(most_recent_entry(matching_entries)) : matching_entries
  raise FileNotFoundError, "File not found: #{@remote_file}" if to_download.size == 0
  download(to_download)
end

#matching_entries(match_name = @remote_file) ⇒ Object



40
41
42
# File 'lib/remi/extractor/sftp_file.rb', line 40

def matching_entries(match_name = @remote_file)
  all_entries.select { |e| match_name.match e.name }
end

#most_recent_entry(entries = matching_entries) ⇒ Object



44
45
46
# File 'lib/remi/extractor/sftp_file.rb', line 44

def most_recent_entry(entries = matching_entries)
  entries.sort_by { |e| e.attributes.createtime }.reverse!.first
end