7

How to generate compressed files on request.

I have this controller

def create    
    send_data generate_tgz("#{RAILS_ROOT}/tmp/example.txt"), :filename => 'export.tgz'    
end

But it gives me a method not found on generate_tgz.

Is it a plugin or gem? Do I need to require anything? Can I generate a zip file instead?

Edit:

def generate_tgz(file)
    system("tar -czf #{RAILS_ROOT}/tmp/export-result #{RAILS_ROOT}/tmp/export")
    content = File.read("#{RAILS_ROOT}/tmp/export-result")
    #ActiveSupport::Gzip.compress(content)    
end

This creates a tgz, but when I decompress it I get app/c3ec2057-7d3a-40d9-9a9d-d5c3fe3ffd6f/home/tmp/export/and_the_files

I would like it to just be: export/the_files

Nerian
  • 15,901
  • 13
  • 66
  • 96
  • Are you talking about the example given on this page http://api.rubyonrails.org/classes/ActionController/Streaming.html? I don't think there's any such method implemented in Rails. It was just an example. – Dogbert Feb 17 '11 at 15:10
  • @Dogbert: Yes, that's the example. – Nerian Feb 17 '11 at 15:13

1 Answers1

3

The method doesn't exist. You can easily create it using ActiveSupport::Gzip.

def generate_tgz(file)
  content = File.read(file)
  ActiveSupport::Gzip.compress(content)
end
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Nice! The only thing I had to change is :filename => 'export.tgz' to :filename => 'export.zip'. And how do I bundle many files into one? – Nerian Feb 17 '11 at 17:24
  • To bundle many file at once you need to create an archive. Rails doesn't support this by default. – Simone Carletti Feb 17 '11 at 17:44
  • I managed to use a shell call to make an archive. Now it works well, except that it creates a rather non friendly directory hierarchy. Check the edit. – Nerian Feb 17 '11 at 19:12