Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you tell if an FTP file exists using ruby?

Tags:

ruby

ftp

open-uri

I'm trying to figure out the best and fastest way to tell if a file exists on an ftp server.

This 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 like just capturing every exception is a bad idea but I had trouble getting the correct specific exception(s).

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

like image 782
hadees Avatar asked Jul 12 '11 18:07

hadees


1 Answers

I think your approach seems fine except for one thing: not all FTP servers support the SIZE command, it was introduced in the Extensions of FTP, so there's no guarantee. Your exception handling is also a bit coarse, as you noticed yourself. I would suggest to rescue FTPReplyError specifically. In case it gives you an indication that SIZE is not implemented (500 or 502) you should probably rely on a fallback, more on that 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 fallback would be to retrieve the list of files with FTP#list, then iterate through them and compare with idx.

like image 143
emboss Avatar answered Sep 29 '22 00:09

emboss