Generating multiple csv files and uploading just one zip file using rails

I am looking for a way to create multiple csv files and download them as one zip archive in one request in my rails app.

I use the rubyzip gem to create the archive - just the built-in send_data function to download it. The problem is that the rubyzip add-function requires a path to download the files. But there is no path as my csv files are being generated in a single request.

Code:

# controller action to download zip
def download_zip
  zip = @company.download_all
  send_data zip, filename: "abc.zip", type: 'application/zip'
end

# method to create zip
def download_all
  Zip::File.open('def.zip', Zip::File::CREATE) do |zipfile|
    self.users.each do |user|
      #some magic to combine zipfile.add() and user.to_csv
    end
  end
end

# method to create csv
def to_csv
  CSV.generate do |csv|
    #build awesome csv
  end
end

      

Is there a way to temporarily store my csv files in some directory so that I can pass the path to zipfile.add ()?

Nice weekend everyone and happy coding!

+3


source to share


2 answers


You can either write your CSV file to a temporary file or call zipfile.add (), but there is a cleaner solution:

zipfile.get_output_stream("#{user.name}.csv") { |f| f.puts(user.to_csv) }

      



For more on get_output_stream see http://rdoc.info/github/rubyzip/rubyzip/master/Zip/File#get_output_stream-instance_method . In addition, you can pass additional parameters to specify the attributes of the generated file.

+2


source


get_output_stream

doesn't work for me. However, the updated method Zip::OutputStream.write_buffer

helps

https://gist.github.com/aquajach/7fde54aa9bc1ac03740feb154e53eb7d



This example adds password protection.

0


source







All Articles