Skip to content

Instantly share code, notes, and snippets.

@guilpejon
Created July 11, 2017 23:18
Show Gist options
  • Save guilpejon/e72ffce66f8fd9f182ddaf8fceaf741d to your computer and use it in GitHub Desktop.
Save guilpejon/e72ffce66f8fd9f182ddaf8fceaf741d to your computer and use it in GitHub Desktop.
Downloading files from S3, zipping them and uploading them to S3 with carrierwave
# METHOD 1: using output stream
def generate_kit_banco_zip(kit_banco)
s3 = Aws::S3::Resource.new
bucket = s3.bucket(ENV['FOG_DIRECTORY'])
compressed_filestream = Zip::OutputStream.write_buffer do |zos|
file = kit_banco.social_contract_file.file
file_obj = bucket.object(file.path)
zos.put_next_entry("ContratoSocial.#{file.extension}")
zos.print(file_obj.get.body.read)
end
compressed_filestream.rewind
temp_zip = Tempfile.new(['kit_documento', '.zip'])
temp_zip.binmode
temp_zip.write(compressed_filestream.read)
kit_banco.zipped_kit_file = File.open(temp_zip)
kit_banco.save!
ensure
temp_zip.close
temp_zip.unlink
end
# METHOD 2
def generate_kit_banco_zip2(kit_banco)
zip_path = Rails.root.join('tmp', 'uploads', SecureRandom.hex(10).to_s + '.zip')
Zip::File.open(zip_path, Zip::File::CREATE) do |zipfile|
file = kit_banco.social_contract_file.file
contract_file = Rails.root.join('tmp', 'uploads', SecureRandom.hex(10).to_s + ".#{file.extension}")
File.open(contract_file, 'wb') do |f|
f.write(file.read)
end
zipfile.add("contrato_social.#{file.extension}", contract_file)
end
kit_banco.zipped_kit_file = File.open(zip_path)
kit_banco.save!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment