Generating Encrypted Zip files in Rails

Sometimes you need to create password-protected zip files in Ruby on Rails. The idea is to create a CSV file first and then add it to a zip file that will be encrypted. For instruction on generating a CSV file, please read this post.

First, add the necessary gems.

# Gemfile

gem 'rubyzip', '>= 1.0.0'
gem 'zip-zip'

Now add a button to export zip files in app/views/posts/index.html.erb.

# app/views/posts/index.html.erb

<%= link_to "Export Zip", posts_path(format: 'zip') %>

In app/controllers/posts_controller.rb, put the following lines of code:

# app/controllers/posts_controller.rb

format.zip do
 compressed_filestream = Zip::OutputStream.write_buffer(::StringIO.new(''), Zip::TraditionalEncrypter.new('admins_only')) do |zos|
   # Users
   zos.put_next_entry 'posts.csv'
   posts = Post.to_csv
   zos.print posts
 end
 compressed_filestream.rewind
 send_data compressed_filestream.read, filename: 'data.zip'
end

There you have it! Happy zipping!