仅当目录不存在时,如何通过 SFTP 在 Ruby 上创建目录?
我现在有以下代码:
Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
sftp.mkdir! remotePath
sftp.upload!(localPath + localfile, remotePath + remotefile)
end
我第一次创建目录没有问题,但它会尝试重新创建相同的目录,即使它已经存在并且它会抛出一个错误。
有人知道怎么做吗?
在使用fileutils时,有这样的代码:
FileUtils.mkdir_p(remotePath) unless File.exists?(remotePath)
我可以通过 SFTP 做同样的事情吗?
最佳答案
在这种情况下,简单地“请求原谅”可能更好,然后再“请求许可”。它还消除了竞争条件,在这种情况下您检查目录是否存在,发现它不存在,然后在创建它时出错,因为它是由其他人同时创建的。
下面的代码会更好:
Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
begin
sftp.mkdir! remotePath
rescue Net::SFTP::StatusException => e
# verify if this returns 11. Your server may return
# something different like 4.
if e.code == 11
# directory already exists. Carry on..
else
raise
end
end
sftp.upload!(localPath + localfile, remotePath + remotefile)
end
关于ruby-on-rails - 如果目录已经存在,则在 Ruby 上通过 SFTP 创建目录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388684/