How to FTP in Ruby without first saving the text f

2020-02-02 12:36发布

Since Heroku does not allow saving dynamic files to disk, I've run into a dilemma that I am hoping you can help me overcome. I have a text file that I can create in RAM. The problem is that I cannot find a gem or function that would allow me to stream the file to another FTP server. The Net/FTP gem I am using requires that I save the file to disk first. Any suggestions?

ftp = Net::FTP.new(domain)
ftp.passive = true
ftp.login(username, password)
ftp.chdir(path_on_server)
ftp.puttextfile(path_to_web_file)
ftp.close

The ftp.puttextfile function is what is requiring a physical file to exist.

标签: ruby ftp heroku
2条回答
等我变得足够好
2楼-- · 2020-02-02 12:58

StringIO.new provides an object that acts like an opened file. It's easy to create a method like puttextfile, by using StringIO object instead of file.

require 'net/ftp'
require 'stringio'

class Net::FTP
  def puttextcontent(content, remotefile, &block)
    f = StringIO.new(content)
    begin
      storlines("STOR " + remotefile, f, &block)
    ensure
      f.close
    end
  end
end

file_content = <<filecontent
<html>
  <head><title>Hello!</title></head>
  <body>Hello.</body>
</html>
filecontent

ftp = Net::FTP.new(domain)
ftp.passive = true
ftp.login(username, password)
ftp.chdir(path_on_server)
ftp.puttextcontent(file_content, path_to_web_file)
ftp.close
查看更多
Root(大扎)
3楼-- · 2020-02-02 13:06

David at Heroku gave a prompt response to a support ticket I entered there.

You can use APP_ROOT/tmp for temporary file output. The existence of files created in this dir is not guaranteed outside the life of a single request, but it should work for your purposes.

Hope this helps, David

查看更多
登录 后发表回答