Using Ruby to create ZIP archives containing UTF-8 encoded “files” without using the file system

StackOverflow https://stackoverflow.com/questions/11953479

Question

Using zipruby it is beautifully easy to create a ZIP archive without writing to disk. One can take strings and add them as archive entries and finally get the entire archive as a string. I can then send it as an attachment to the web service that is expecting such an archive. This is exactly what I need with one exception: it turns out that the files in the archive are US-ASCII encoded, whereas the web service is very strict about the files being UTF-8 encoded.

Is there a way to get zipruby (or some equivalent tool, although I haven't found one for Ruby capable of not using temporary files) to encode these archive entries as UTF-8?

zipped_data = ''
Zip::Archive.open_buffer zipped_data, Zip::CREATE do |archive|
  archive.add_buffer 'file1.xml', xml1.encode('UTF-8')
  archive.add_buffer 'file2.xml', xml2.encode('UTF-8')
end

To test, I write the zipped_data to a file, then unzip, and then I can see very well the encoding is wrong:

$ file -bi file1.xml
application/xml; charset=us-ascii
Was it helpful?

Solution

This likely just means that there are no multibyte chars in the file to identify it as utf8. In other words a utf8-encoded file with only ascii chars in it should be identified as ascii.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top