编写一个通过 SFTP 检查服务器上是否存在文件的函数。
我写了一个有效的函数sftp_file_exists_1?
。现在我想将此函数拆分为两个函数,令我惊讶的是,这不起作用。
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")
我期望:
true
true
因为文件repos
实际上存在于服务器上。但是,我得到(缩写):
true
#<Net::SFTP::Request:0x000055f3b56732d0 @callback=#<Proc:0x000055f3b5673280@./test.rb:14>, ...
附录:这有效:
def sftp_stat_ok?(sftp, filename)
begin
sftp.stat!(filename)
rescue Net::SFTP::StatusException
return false
end
return true
end