How to find out if an FTP file exists using ruby?

I am trying to figure out the best and fastest way to find out if a file exists on an ftp server.

Here is what I came up with ...

def remote_exists?(idx) #@file.rewind if @file.eof? ftp = Net::FTP.new(FTP_SERVER) ftp.login begin ftp.size(idx) rescue Exception return false end true end 

It seems that just catching each exception is a bad idea, but I have not been able to get the correct specific exception.

I also use OpenURI in my code to actually get the file. I was trying to figure out if this might have some method that could be better, but I think it just uses Net :: FTP anyway.

+6
source share
1 answer

I think your approach seems fine, except for one thing: not all FTP servers support the SIZE command, it was introduced in the FTP Extensions , so there is no guarantee. Your exception handling is also a little rude, as you yourself noticed. I would suggest saving FTPReplyError in particular. In case this gives you an indication that SIZE is not implemented (500 or 502), you should probably rely on a backup, moreover, after the updated code:

 def remote_exists?(idx) ftp = Net::FTP.new(FTP_SERVER) ftp.login begin ftp.size(idx) rescue FTPReplyError => e reply = e.message err_code = reply[0,3].to_i unless err_code == 500 || err_code == 502 # other problem, raise raise end # fallback solution end true end 

A viable rollback would be to get a list of files using FTP#list , and then iterate over them and compare with idx .

+11
source

Source: https://habr.com/ru/post/892609/


All Articles