如何在 Ruby 中使用 FTP 而不先保存文本文件 [英] How to FTP in Ruby without first saving the text file

查看:19
本文介绍了如何在 Ruby 中使用 FTP 而不先保存文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

ftp.puttextfile 函数要求物理文件存在.

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

推荐答案

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

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

这篇关于如何在 Ruby 中使用 FTP 而不先保存文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆