How to create zip file only in memory in ruby?

青春壹個敷衍的年華 提交于 2019-12-04 04:23:51

问题


I want to create a zip file of all HTML files in a given directory. The zip will be sent as an attachment via email along with the rest of the files from the directory. All email clients I tried so far have trouble reading an email if any attachment is a HTML file, if I send from pony. So I thought I'd zip them.

Is there any way to zip the HTML files on the fly but really only in the memory, without using any temp files on Windows platform? Preferably not using any external program?

If I understood right, both methods described in:

  • http://info.michael-simons.eu/2008/01/21/using-rubyzip-to-create-zip-files-on-the-fly/ or
  • http://rubyzip.sourceforge.net/classes/Zip/ZipFile.html

are using some kind of temp file.


回答1:


At first I thought maybe you could use a StringIO object to write to, but it looks like the ZipOutputStream class insists on opening a temporary file.

If you don't mind calling an external program, standard linux zip can be told to send otuput to stdout instead of a file by using "-" instead of a filename. So just collect the output into a variable then do whatever you like with it.

zipdata = %x(zip -q - *.html)

I don't think this is going to be an efficiency gain over just using a temporary file, but you'd have to measure it to be sure.



来源:https://stackoverflow.com/questions/11532502/how-to-create-zip-file-only-in-memory-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!