如何在没有先保存文本文件的情况下在Ruby中进行FTP

sca*_*er2 12 ruby ftp heroku

由于Heroku不允许将动态文件保存到磁盘,我遇到了一个两难的境地,我希望你能帮我克服.我有一个可以在RAM中创建的文本文件.问题是我找不到允许我将文件流式传输到另一个FTP服务器的gem或函数.我正在使用的Net/FTP gem需要先将文件保存到磁盘.有什么建议?

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
Run Code Online (Sandbox Code Playgroud)

ftp.puttextfile函数是需要物理文件存在的函数.

cia*_*tek 19

StringIO.new提供了一个像打开文件一样的对象.通过使用StringIO对象而不是文件来创建像puttextfile这样的方法很容易.

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
Run Code Online (Sandbox Code Playgroud)


sca*_*er2 5

Heroku的大卫迅速回应了我进入那里的支持票.

您可以使用APP_ROOT/tmp进行临时文件输出.在单个请求的生命周期内,不保证在此目录中创建的文件的存在,但它应该适用于您的目的.

大卫,希望这会有所帮助