如何使用 Net::SFTP 和 Ruby 检查条目是文件还是目录

How to check if entry is file or directory with Net::SFTP and Ruby

使用 Net::SFTPdir 我试图确定哪些条目是文件和目录。不确定要检查什么:

Net::SFTP.start(server_ip, ftp_username, :password => ftp_password, :port => ssh_port, :timeout => 6) do |sftp|
        files = sftp.dir.entries(path).select{|entry| ??? }
        directories = sftp.dir.entries(path).select{|entry| ??? }
end

解决方案

您可以使用:

files, directories = sftp.dir.entries(path).partition{ |entry| entry.file? }

例子

p files.map(&:name)
# ["Gemfile", "Gemfile.lock", ".gitignore", "README.rdoc", "Rakefile", "sftp_pv.expect", "config.ru"]
p directories.map(&:name)
# ["data", "config", "..", "app", "tmp", "public", "vendor", "test", ".git", ".", "log", "bin", "lib", "db"]

如何找到解决方案?

我复制了你的代码,定义了连接到个人服务器所需的所有变量,并将 path 定义到远程 Rails 项目。

我把你的区块改成了 p sftp.dir.entries(path).first

结果出来了:

#<Net::SFTP::Protocol::V01::Name:0x00000000dbf3f8 @name="data", @longname="drwxr-xr-x    2 dev      dev         20480 Oct 27 10:45 data", @attributes=#<Net::SFTP::Protocol::V01::Attributes:0x00000000dbf5b0 @attributes={:size=>20480, :uid=>1002, :gid=>1003, :permissions=>16877, :atime=>1482015468, :mtime=>1477557907}>>

谷歌搜索 Net::SFTP::Protocol::V01::Name 将我带到了 documentation

directory? and file? 很有前途的名字!

这个:

p sftp.dir.entries(path).first.file?

已返回 false

最后,我记得在同一个块中使用 rejectselect 可以缩短为 partition :

Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.