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.
1
2
3
4
# Gemfile
gem 'rubyzip', '>= 1.0.0'
gem 'zip-zip'
Now add a button to export zip files in app/views/posts/index.html.erb
.
1
2
3
# 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:
1
2
3
4
5
6
7
8
9
10
11
12
# 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!