Lau*_*ona 5 ruby directory sftp ruby-on-rails fileutils
仅当目录不存在时,如何才能通过 SFTP 在 Ruby 上创建目录?
我现在有以下代码:
Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
sftp.mkdir! remotePath
sftp.upload!(localPath + localfile, remotePath + remotefile)
end
Run Code Online (Sandbox Code Playgroud)
我第一次创建目录没有问题,但它会尝试重新创建相同的目录,即使它已经存在并且它会抛出一个错误。
有谁知道如何做到这一点?
在使用 fileutils 时,有这样的代码:
FileUtils.mkdir_p(remotePath) unless File.exists?(remotePath)
Run Code Online (Sandbox Code Playgroud)
有什么办法可以通过 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2728 次 |
| 最近记录: |