Class: Services::FtpServer

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
app/models/services/ftp_server.rb

Constant Summary collapse

PRIVATE_KEY_FILE =

Allow the private key path to be overridden. The default is the production location

defined?(SSH_PRIVATE_KEY) ? SSH_PRIVATE_KEY : '/etc/pki/abaqis/abaqis_rsa'

Instance Method Summary collapse

Constructor Details

#initialize(hostname, username, password, base_directory = '/') ⇒ FtpServer

Returns a new instance of FtpServer.



10
11
12
13
14
15
# File 'app/models/services/ftp_server.rb', line 10

def initialize(hostname, username, password, base_directory='/')
  @hostname = hostname
  @username = username
  @password = password
  @base_directory = base_directory
end

Instance Method Details

#connectObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/models/services/ftp_server.rb', line 17

def connect
  
  options = {
    password: @password, 
    auth_methods: %w{ publickey password }
  }
  # Add the private key to the list if available
  options[:keys] = PRIVATE_KEY_FILE if File.exists?(PRIVATE_KEY_FILE)

  Net::SFTP.start(@hostname, @username, options) do | sftp |
    @sftp = sftp
    begin
      yield self
    ensure
      @sftp = nil
    end
  end
end

#download_file(from_dir, file, to_directory) ⇒ Object



52
53
54
55
56
# File 'app/models/services/ftp_server.rb', line 52

def download_file(from_dir, file, to_directory)
  raise "Must be called within the block of a connect!" if @sftp.nil?
  mkdir_p to_directory
  @sftp.download! path(from_dir, file), File.join(to_directory, file)
end

#download_files(from_dir, files, to_directory) ⇒ Object



48
49
50
# File 'app/models/services/ftp_server.rb', line 48

def download_files(from_dir, files, to_directory)
  files.each { | file | download_file from_dir, file, to_directory }
end

#file_list(in_dir, with_glob = '*') ⇒ Object



42
43
44
45
46
# File 'app/models/services/ftp_server.rb', line 42

def file_list(in_dir, with_glob='*')
  raise "Must be called within the block of a connect!" if @sftp.nil?
  dir = path(in_dir)
  @sftp.dir.glob(dir, with_glob).select { | entry | entry.file? }.map { | entry | entry.name }
end

#path(subdir, file_name = nil) ⇒ Object



36
37
38
39
40
# File 'app/models/services/ftp_server.rb', line 36

def path(subdir, file_name=nil)
  parameters = [ @base_directory, @username, subdir ]
  parameters << file_name unless file_name.nil?
  File.join(*parameters)
end

#remove_file(from_dir, file) ⇒ Object



62
63
64
65
# File 'app/models/services/ftp_server.rb', line 62

def remove_file(from_dir, file)
  raise "Must be called within the block of a connect!" if @sftp.nil?
  @sftp.remove! path(from_dir, file)
end

#remove_files(from_dir, files) ⇒ Object



58
59
60
# File 'app/models/services/ftp_server.rb', line 58

def remove_files(from_dir, files)
  files.each { | file | remove_file from_dir, file } unless files.nil?
end