Writing a function that checks via SFTP if a file is present on the server.
I have written a function sftp_file_exists_1?
that works. Now I want to split this function into two functions, and to my surprise, this does not work.
require "net/sftp"
def sftp_file_exists_1?(host, user, filename)
Net::SFTP.start(host, user, verify_host_key: :always) do |sftp|
sftp.stat(filename) do |response|
return response.ok?
end
end
end
def sftp_stat_ok?(sftp, filename)
sftp.stat(filename) do |response|
return response.ok?
end
end
def sftp_file_exists_2?(host, user, filename)
Net::SFTP.start(host, user, verify_host_key: :always) do |sftp|
return sftp_stat_ok?(sftp, filename)
end
end
p sftp_file_exists_1?("localhost", "user", "repos")
p sftp_file_exists_2?("localhost", "user", "repos")
I expected:
true
true
since a file repos
actually exists on the server. However, I get (abbreviated):
true
#<Net::SFTP::Request:0x000055f3b56732d0 @callback=#<Proc:0x000055f3b5673280@./test.rb:14>, ...
Addendum: this works:
def sftp_stat_ok?(sftp, filename)
begin
sftp.stat!(filename)
rescue Net::SFTP::StatusException
return false
end
return true
end