vendredi 14 avril 2023

Ruby: creating a Zip file

I have following code that I use for create .gz.tar file but now I need to change it to .zip formant


create_tarball = lambda do |tarball, files, config, id|
  File.open(tarball, 'wb') do |t|
    Zlib::GzipWriter.wrap(t) do |gz|
      Gem::Package::TarWriter.new(gz) do |tar|
        content = "#{config.join("\n")}\n"
        tar.add_file_simple("file.example", 0o644, content.length) do |io|
          io.write(content)
        end
        files.each do |file|
          mode = File.stat(file).mode
          File.open(file, 'rb') do |f|
            tar.add_file_simple(File.basename(file), mode, f.size) do |io|
              io.write(f.read)
            end
          end
        end
      end
    end
  end
end

how can i convert this logic to do same thing but into a Zipfile, please help

i tried to do this but it doesn't work

create_tarball = lambda do |tarball, files, config, id|
  File.open(tarball, 'wb') do |t|
    Zip::File.open(zipfile_name, create: true) do |zipfile|
      Zip::OutputStream.write_buffer do |zip|
        content = "#{config.join("\n")}\n"
        zip.put_next_entry("file.example")
        zip.write(content)
        end
        files.each do |file|
          mode = File.stat(file).mode
          File.open(file, 'rb') do |f|
            tar.add_file_simple(File.basename(file), mode, f.size) do |io|
              io.write(f.read)
            end
          end
        end
      end
    end
  end
end

Aucun commentaire:

Enregistrer un commentaire