Skip to content

Instantly share code, notes, and snippets.

@mfifth
Created April 13, 2018 02:16
Show Gist options
  • Save mfifth/63a76e3333ff8be19012178cd11ec199 to your computer and use it in GitHub Desktop.
Save mfifth/63a76e3333ff8be19012178cd11ec199 to your computer and use it in GitHub Desktop.
def sort_files(file_params, ar_object) # Active Record Object
if file_params.values.count >= 2 # <- If there are more than two files being submitted.
tmp_filename = "#{Rails.root}/tmp/" << Time.now.strftime('%Y-%m-%d-%H%M%S-%N').to_s << ".zip" # <- Unique file name
file_count = 0
Zip::File.open(tmp_filename, Zip::File::CREATE) do |zipfile| # <- Find or create a file with this name
file_params.values.each do |file| # <- Loop over all the files in the array.
new_filename = "#{file_count += 1}-#{file.original_filename}"
puts new_filename
zipfile.add(new_filename, file.path) # <- Add file to zip.
end
zipfile.close # <- Close the zip stream.
end
zipped_file = File.open(tmp_filename) # <- Hold a reference to the zipfile.
ar_object.csv_file = zipped_file
File.delete(zipped_file.path) if File.exist?(zipped_file.path) # <- Cleanup tmp folder.
puts "#{ar_object.inspect}"
else
file = file_params.values.first
ar_object.csv_file = file
puts "#{ar_object.inspect}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment