[RAILS] If you want to make a zip file with Ruby, it's rubyzip.

Overview

I had to create a lot of zip files for a certain task, but I was saved by encountering this gem. This article introduces four ways to work with zip files using ruby.

Ruby version

Ruby 2.4 or higher

install gem

Add to Gemfile

Gemfile


gem 'rubyzip'

Run the following command in the terminal

terminal


bundle install

Use properly for 4 purposes

1. Create a zip file

Zip::OutputStream.open('example.zip') do |zos|
  zos.put_next_entry('first_file.txt')
  zos.puts 'hoge hoge'

  zos.put_next_entry('second_file.txt')
  zos.puts 'hoge again'
end

Use a string or the data read from the file as an argument to the puts method. The contents of the generated zip file have the following structure.

example.zip
- first_file.txt
- second_file.txt

The contents of each file are as follows.

first_file.txt


hoge hoge

second_file.txt


hoge again

2. Read the zip file

The files in the zip file are set one after another by the get_next_entry method.

Zip::InputStream.open('example.zip') do |zis|
  entry = zis.get_next_entry
  print "First line of '#{entry.name} (#{entry.size} bytes):  "
  puts "'#{zis.gets.chomp}'"
  entry = zis.get_next_entry
  print "First line of '#{entry.name} (#{entry.size} bytes):  "
  puts "'#{zis.gets.chomp}'"
end

If you read the ʻexample.zip` generated in ** 1 **, you will see the following.

terminal


First line of 'first_file.txt (10 bytes):  hoge hoge
First line of 'second_file.txt (11 bytes):  hoge again

3. Read the zip file directory

Use the get_input_stream (entry) method to get the ʻInputStream` for each entry.

zf = Zip::File.new('example.zip')
zf.each_with_index do |entry, index|
  puts "entry #{index} is #{entry.name}, size = #{entry.size}, compressed size = #{entry.compressed_size}"
end

This source code displays the compressed files ʻindex, name, size, compressed_size` in a zip file.

If you read the ʻexample.zip` generated in ** 1 **, you will see the following.

terminal


entry 0 is first_file.txt, size = 10, compressed size = 10
entry 1 is second_file.txt, size = 11, compressed size = 13

4. Modify the zip file

Modify the zip file directly

Add the file indicated by path with ʻadd (entry, path) Rename withrename (entry, new_name)`

Modify the file generated by ** 1 **

Zip::File.open('example.zip') do |zip_file|
  zip_file.add('third_file.txt', 'third_file.txt')
  zip_file.rename('first_file.txt', 'first_file_rename.txt')
  zip_file.add('fourth_file.txt', 'fourth_file.txt')
end

The following files are additionally prepared.

third_file


hoge third

fourth_file


hogehoge fourth

I will try it. Get information using ** 3 **

terminal


entry 0 is second_file.txt, size = 11, compressed size = 13
entry 1 is third_file.txt, size = 10, compressed size = 12
entry 2 is first_file_rename.txt, size = 10, compressed size = 10
entry 3 is fourth_file.txt, size = 14, compressed size = 14

The generated zip file has been modified to have the following structure:

example.zip
- second_file_txt
- third_file.txt
- first_file_rename.txt
- fourth_file.txt

Summary

In this article, I have introduced four ways to work with zip files. There are other useful methods in rubyzip, so it is recommended to take a look.

reference

https://github.com/rubyzip/rubyzip

Recommended Posts

If you want to make a zip file with Ruby, it's rubyzip.
I want to monitor a specific file with WatchService
If you want to use Mockito with Kotlin, use mockito-kotlin
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Learning Ruby with AtCoder 13 How to make a two-dimensional array
I want to create a Parquet file even in Ruby
If you want to make a Java application a Docker image, it is convenient to use jib.
Make a typing game with ruby
How to make a jar with old Hadoop (hadoop-core-0.20.2-cdh3u6) in Gradle: (What to do if you get Could not expand ZIP ..)
I want to make a button with a line break with link_to [Note]
I want to add a browsing function with ruby on rails
How to make a jar file with no dependencies in Maven
Try to make a cross-platform application with JRuby (jar file generation)
If you dare to compare Integer with "==" ...
[Swift] If you want to use a URL that includes Japanese, use addingPercentEncoding.
I want to download a file on the Internet using Ruby and save it locally (with caution)
It's a pain to deal with old dates
What to do when you want to delete a migration file that is "NO FILE"
If it is Ruby, it is efficient to make it a method and stock the processing.
If you want to modify database columns etc.
I want to be able to read a file using refile with administrate [rails6]
[Ruby] I want to do a method jump!
[Ruby] I want to make an array from a character string with the split method. And vice versa.
[Ruby] When you want to replace multiple characters
[Ruby] I want to make a program that displays today's day of the week!
If you use SQLite with VSCode, use the extension (how to see the binary file of sqlite3)
How to make a factory with a model with polymorphic association
If you want to separate Spring Boot + Thymeleaf processing
How to make LINE messaging function made with Ruby
Let's make a LINE Bot with Ruby + Sinatra --Part 2
What to do if you accidentally create a model
If you want to recreate the instance in cloud9
Let's make a LINE Bot with Ruby + Sinatra --Part 1
If hash [: a] [: b] [: c] = 0 in Ruby, I want you to extend it recursively even if the key does not exist.
[Ruby + Rails] When you want to register in Mailchimp's mail list together with user registration
What to do if you installed Ruby with rbenv but the version does not change
How to request a CSV file as JSON with jMeter
[Ruby] How to split each GraphQL query into a file
What to do if you get a java.io.IOException in GlassFish
How to divide a two-dimensional array into four with ruby
[Beginner] Try to make a simple RPG game with Java ①
If you want to study programming at university, go to Australia
[# 3 Java] Read this if you want to study Java! ~ Carefully selected ~
I want to make a specific model of ActiveRecord ReadOnly
In Ruby you can define a method with any name
[Easy] How to automatically format Ruby erb file with vsCode
When you want to explicitly write OR or AND with ransack
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
docker-compose.yml when you want to keep mysql running with docker
lombok.config when you want to pass @Qualifier to @RequiredArgsConstructor with lombok
It's not a big deal if you understand that I was addicted to receiving emails with Java Mail from Exchange Online
[Swift] When you want to know if the number of characters in a String matches a certain number ...
If you are new to Rails and want to make your own validation, stop by this finger.
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
[Output] Learn Ruby from what you want to do at the fastest speed-Part 2 "Create a flowchart"
When installing a gem with C extension in Ruby, I want to finish it quickly using multiple CPU cores like make -j4
[Ruby] problem with if statement
What to do if you get a gcc error in Docker
I want to hook log file generation / open with log4j # FileAppender
[PostgreSQL] If you want to delete the Rails app, delete the database first!