Search code examples
rubyfileioftptransfer

Is it possible to transfer the contents of a whole directory using the built in Ruby Net::FTP class?


I'm building an application in Ruby that has a command which will transfer the contents of a certain directory to a remote FTP server. I know that the way to transfer a single file via ftp in Ruby is:

file = File.open('file.txt')
    Net::FTP.open(ftp_server, username, password) { |ftp|
    ftp.putbinaryfile(file)
}

I just don't know how to transfer the contents of a directory via the build in FTP class. If somebody could give me an example of how to do this, or knows of a Ruby library that can do this it would be much appreciated.


Solution

  • First, get all files and subdirectories in your directory:

    entries = Dir.glob('my_dir/**/*').sort
    

    (sort is required to ensure that every directory goes before its files)

    Now you can upload all files and create all subdirectories:

    Net::FTP.open(ftp_server, username, password) do |ftp|
      entries.each do |name|
        if File::directory? name
          ftp.mkdir name
        else
          File.open(name) { |file| ftp.putbinaryfile(file, name) }
        end
      end
    end
    

    I had no time to test this, so I could miss something.