How can I generate zip file without saving to the disk with Ruby?

后端 未结 5 1341
既然无缘
既然无缘 2020-12-05 06:41

I have generated many PDF files in memory and I want to compress them into one zip file before sending it as a email attachment. I have looked at Rubyzip and it does not all

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 07:14

    The accepted answer works well but it didn't solve my problem. I didn't want to use the write_buffer method because it automatically closes the stream after the block closes. The code snippet below gives you more control over when the stream is created and closed.

    require 'stringio'
    require 'zip'
    
    io = StringIO.new
    zip_io = Zip::OutputStream.new(io, true) # 'true' indicates 'io' is a stream
    zip_io.put_next_entry('test.txt')
    zip_io.write('Hello world!')
    
    # Read the data and close the streams
    io.rewind
    binary_data = io.read
    zip_io.close_buffer
    io.close
    

提交回复
热议问题