Rails: How can I use system zip on Heroku to make

2019-02-27 05:53发布

问题:

I have this working locally, storing the template files in #{Rails.root}/tmp, using system "cd tmp/template; zip -r ../#{@filename} *" to zip up the files, sending the .docx (zip archive) to S3 and then to the browser. The problem is that Heroku is not finding the files. Before I create the xml file, I am copying the template directory from another location (system "cp -R support/ser_template tmp/"). I understand Heroku's read-only filesystem but I can't have #{Process.pid}'s littering my filenames (Word requires the xml file to be named document.xml).

Is there anyway I can store the template files on Amazon and still use Heroku's system zip utility? RubyZip does not create proper docx archives.

Edit: here is the code:

require 'aws/s3'

class WordDocument
  include ConnectS3

  def initialize(content)
    connect_s3
    @pid = Process.pid
    @filename = "SER_" + Time.now.strftime("%Y%m%d-%H%M%S") + '.docx'
    system "cp -R #{Rails.root}/support/ser_template #{temp_path}"
    xml = File.open(xml_path, 'w')
    xml.puts content
    xml.close
    system "cd #{temp_path}; zip -r #{@filename} *"
    docx = File.open(temp_path + "/" + @filename, 'r')
    AWS::S3::S3Object.store(s3_path, docx, @s3_credentials["bucket"], :use_virtual_directories => true)
    AWS::S3::S3Object.grant_torrent_access_to s3_path, @s3_credentials["bucket"]
  end

  def temp_path
    "#{Rails.root}/tmp/#{@pid}_ser"
  end

  def xml_path
    temp_path + "/word/document.xml"
  end

  def path
    "https://s3.amazonaws.com/" + @s3_credentials["bucket"] + s3_path
  end

  def s3_path
    '/section_editor_reports/' + @filename
  end
end

回答1:

Can't you just a create directory within #{Rails.root}/tmp called, say, #{Process.pid}_docx/something_nice/? Copy (or symlink) what you need into:

#{Rails.root}/tmp/#{Process.pid}_docx/something_nice/

Then

system "cd #{Rails.root}/tmp/#{Process.pid}_docx/; zip -r x.zip something_nice"

And then you have:

#{Rails.root}/tmp/#{Process.pid}_docx/x.zip

With a nice pretty internal structure that doesn't include your PID.