ruby-on-rails - 如果目录已经存在,则在 Ruby 上通过 SFTP 创建目录失败

标签 ruby-on-rails ruby directory sftp fileutils

仅当目录不存在时,如何通过 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/

相关文章:

html - 如何在 ERB (Rails) 中包装父 div 中的每个 N 元素?

ruby-on-rails - Rails 3 工厂与简单实例化

ruby-on-rails - 多个模型的多个图像 - Paperclip、Rails

html - 仅当数据库中存在图像时如何设置div的动态背景图像

ruby - !~ 方法对 Ruby 中的字符串有什么作用

php - 读取文件夹并将子文件夹名称拆分为 MySQL 插入

Mysql 使用新的数据库位置创建数据库

ruby - 直接在 ruby​​ 中使用实例变量是不好的形式吗?

ruby - 如何转义 Ruby 字符串插值?

windows - Cakephp - 使用 Folder::cd() 更改目录(绝对 Windows 路径)不起作用