delete/remove temp zip file in ruby on rails - ruby-on-rails

i am creating temp zip file in rails tmp directory as follows:-
zipfile_name = Rails.root.join("tmp/abc.zip")
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir[File.join(data, '**',)].each do |file|
zipfile.add(file.sub(dir+"/", ''), file)
end
end
zip_data = File.read(zipfile_name) # sending zip file.
zipfile_name.try(:unlink)` # try to remove or unlink the zip but not working.
temp zipfile_name was abc.zip20140816-8931-1yl3g60 and i want to delete it after sending but it's not found.

File.delete(zipfile_name)
Try file delete command it should work out.

Related

No such file or directory # rb_sysopen -

I want to resolve this error.
No such file or directory # rb_sysopen - zipUpTest/1051687701.jpg
The following is the source code.
Zip::File.open_buffer(obj) do |zip|
zip.each do |entry|
ext = File.extname(entry.name)
file_name = File.basename(entry.name)
next if ext.blank? || file_name.count(".") > 1
dir = File.join(dir_name, File.dirname(entry.name))
FileUtils.mkpath(dir.to_s)
zip.extract(entry, entry.name) {true}
file_name.force_encoding("UTF-8")
file_new_name = "#{dir_name}/#{file_name}"
File.rename(entry.name, file_new_name)
#input_dir << file_new_name
end
end
end
Zip::OutputStream.open(zip_file.path) do |zip_data|
#input_dir.each do |file|
zip_data.put_next_entry(file)
zip_data.write(File.read(file.to_s))
end
end
That means there is no file, how to deal with this problem?
You have to ensure the file zipUpTest/1051687701.jpg exists relative to where the process was run, not where the program is saved.
For example, let's say your program is /home/taizo/program. If you're in /home/taizo and run ruby program then it will look for /home/taizo/zipUpTest/1051687701.jpg. If you're in /tmp and run ruby /home/taizo/program the program will look for /tmp/zipUpTest/1051687701.jpg.

how to add password to already existing zip file using ruby on rails

I have created a ZIP file using ruby , now I have to add password to this file. But it is not working. Could someone help. I am using rubyzip and zip-zip gem.
Code which I tried as below :
#Create Zip File and delete if already existing
filename= 'abc.xlsx'
zip_file_path = Rails.root.join('tmp/my.zip')
file_name =filename
file_path = Rails.root.join('tmp', filename)
logger.error zip_file_path
logger.error file_path
File.delete(zip_file_path) if File.exist?(zip_file_path)
Zip::ZipFile.open(zip_file_path, Zip::ZipFile::CREATE) do |zip|
zip.add(file_name, file_path)
end
# end
Next step is to add password to ZIP file . I tried below method
Zip::File.encrypt(zip_file_path, 'password')
# Got error like : **NameError (uninitialized constant Zip::Archive):**
Also i tried to use below :
Zip::OutputStream.write_buffer(::StringIO.new(''), Zip::TraditionalEncrypter.new('password')) do |out|
out.put_next_entry("my_file.txt")
out.write my_data
end.string
#error: **NameError (uninitialized constant Zip::TraditionalEncrypter):**

irb `initialize': No such file or directory # rb_sysopen -

I try to modify paperclip image from my model after a server change.
I have a file with id of my model and name of image like that
3;3da442247510f15c07fead8f41cd1c9441694b02.jpg
4;e3b652bfe16759002d6dd3da608475069df1c02e.jpg
5;0699ab4040c4d4f6e8ec390170014661bc5f6d96.jpg
I have write a script to find the file and give ti to my model
File.open("titi.txt", "r") do |f|
f.each_line do |line|
tab=line.split(";")
puts "id => #{tab[0]} | nom => #{tab[1]}"
c=Contact.find(tab[0])
file = File.open("#{Rails.root}/public/system/contact/#{tab[1]}")
c.photo = file
file.close
c.save!
end
end
I launch my script like that
RAILS_ENV=production rails runner script.rb
But I have this error
script.rb:6:in `initialize': No such file or directory # rb_sysopen - /var/www/contactmedia/public/system/contact/3da442247510f15c07fead8f41cd1c9441694b02.jpg (Errno::ENOENT)
but when I do
ls -la /var/www/contactmedia/public/system/contact/3da442247510f15c07fead8f41cd1c9441694b02.jpg
I have a file....
What is wrong in my script ? Whant can I test to move my images.
Thanks
EDIT
it's OK i have found why I read a windows file so i have a \r at end of line. I read my file like that now
file = File.open("#{Rails.root}/public/system/contact/#{tab[1].chom‌​p}")

Zipping a directory recursively & skip container directory

Consider, we have following directory structure:
Location:
/Users/me/Desktop/directory_to_zip/
dir1 dir2 somefile.txt
now, If I use rubyzip to zip the contents of directory_to_zip using the following code:
directory = '/Users/me/Desktop/directory_to_zip/'
zipfile_name = '/Users/me/Desktop/recursive_directory.zip'
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir[File.join(directory, '**', '**')].each do |file|
zipfile.add(file.sub(directory, ''), file)
end
end
This will create a zip file named recursive_directory.zip, which will contain a container directory called directory_to_zip & inside directory_to_zip, will I find my files(dir1 dir2 somefile.txt)
HOw do I skip creation of directory_to_zip inside recursive_directory.zip, so that the zip file just contains the contents of directory_to_zip & not the directory itself.
Okay, I solved this on my own. If you are in same boat, here is here how I did it:
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
Dir.chdir directory
Dir.glob("**/*").reject {|fn| File.directory?(fn) }.each do |file|
puts "Adding #{file}"
zipfile.add(file.sub(directory + '/', ''), file)
end
end
This works exactly I want. the limitation here here is that it doesn't handle empty directories. Hopefully, it would help someone.

Download all files to a zip within Heroku

I've been knocking my head around with Heroku, while trying to download a zip file with all my receipt files data.
The files are stored on amazon s3 and it all works fine on my development machine..
I thought it had to do with Tempfile, and abandoned that previous solution, since heroku has some strict policies with their filesystem, so i used the tmp folder, but the problem doesn't seem to be there. I already tried to load directly from s3 (using openUri) to the zip file, but it doesn't seem to work either on Heroku.
What might be wrong with my code for Heroku not loading the files to the zip?
Here is my model method :
def zip_receipts(search_hash=nil)
require 'zip/zip'
require 'zip/zipfilesystem'
t=File.open("#{Rails.root}/tmp/#{Digest::MD5.hexdigest(rand(12).to_s)}_#{Process.pid}",'w')
# t = Tempfile.new(Digest::MD5.hexdigest(rand(12).to_s))
# Give the path of the temp file to the zip outputstream, it won't try to open it as an archive.
Zip::ZipOutputStream.open(t.path) do |zos|
logger.debug("search hash Zip: #{search_hash.inspect}")
self.feed(search_hash).each do |receipt|
begin
require 'open-uri'
require 'tempfile'
#configures filename
filen = File.basename(receipt.receipt_file_file_name)
ext= File.extname(filen)
filen_noext = File.basename(receipt.receipt_file_file_name, '.*')
filen=filen_noext+SecureRandom.hex(10)+ext
logger.info("Info Zip - Filename: #{filen}")
# Create a new entry on the zip file
zos.put_next_entry(filen)
# logger.info("Info Zip - Added entry: #{zos.inspect}")
# Add the contents of the file, reading directly from amazon
tfilepath= "#{Rails.root}/tmp/#{File.basename(filen,ext)}_#{Process.pid}"
open(tfilepath,"wb") do |file|
file << open(receipt.authenticated_url(:original),:ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).read
end
zos.print IO.binread tfilepath
# logger.info("Info Zip - Extracted from amazon: #{zos.inspect}")
rescue Exception => e
logger.info("exception #{e}")
end # closes the exception begin
end #closes receipts cycle
end #closes zip file stream cycle
# The temp file will be deleted some time...
t.close
#returns the path for send file controller to act
t.path
end
My controller:
def download_all
#user = User.find_by_id(params[:user_id])
filepath = #user.zip_receipts
# Send it using the right mime type, with a download window and some nice file name.
send_file(filepath,type: 'application/zip', disposition: 'attachment',filename:"MyReceipts.zip")
end
And I write also my view and routes, so that it might serve anyone else trying to implement a download all feature
routes.rb
resources :users do
post 'download_all'
end
my view
<%= link_to "Download receipts", user_download_all_path(user_id:user.id), method: :post %>
The problem seemed to be with the search hash, and the sql query, and not the code itself. For some reason, the receipts get listed, but aren't downloaded. So it is an all different issue
In the end i have this code for the model
def zip_receipts(search_hash=nil)
require 'zip/zip'
require 'zip/zipfilesystem'
t=File.open("#{Rails.root}/tmp/MyReceipts.zip_#{Process.pid}","w")
# t = Tempfile.new(Digest::MD5.hexdigest(rand(12).to_s))
#"#{Rails.root}/tmp/RecibosOnline#{SecureRandom.hex(10)}.zip"
puts "Zip- Receipts About to enter"
# Give the path of the temp file to the zip outputstream, it won't try to open it as an archive.
Zip::ZipOutputStream.open(t.path) do |zos|
self.feed(search_hash).each do |receipt|
begin
require 'open-uri'
require 'tempfile'
filen = File.basename(receipt.receipt_file_file_name)
ext= File.extname(filen)
filen_noext = File.basename(receipt.receipt_file_file_name, '.*')
filen=filen_noext+SecureRandom.hex(10)+ext
# puts "Info Zip - Filename: #{filen}"
# Create a new entry on the zip file
zos.put_next_entry(filen)
zos.print open(receipt.authenticated_url(:original),:ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).read
rescue Exception => e
puts "exception #{e}"
end # closes the exception begin
end #closes receipts cycle
end #closes zip file stream cycle
# The temp file will be deleted some time...
t.close
#returns the path for send file controller to act
t.path
end

Resources