Rails - Using Tempfile to write on Heroku?

懵懂的女人 提交于 2020-01-01 06:58:25

问题


I need to be able to write a temporary file for use during the request only.

Locally I can use the following successfully:

    tempfile = File.open(a.original_filename,'w')
    tempfile.write_nonblock(a.body)        
      paperclip stuff........
    tempfile.close 

That works great, but not on Heroku... How can I do the above with Heroku's restrictions: link text

I'm not understanding how to translate the above into: #{RAILS_ROOT}/tmp/myfile_#{Process.pid}

Thanks for any help you can provide here.


回答1:


I have a solution for you if you have to do stuff with paperclip. Include this class in your lib folder as heroku_compliant_file.rb

class HerokuCompliantFile < StringIO
  def initialize(str,filename,content_type)
    @original_filename = filename
    @content_type = content_type
    super(str)
  end
end

In your model containing the paperclip -

def insert_a_hunk_of_string_into_paperclip(some_object)
  f = HerokuCompliantFile.new(some_object.render,"myfile_#{Process.pid}","application/pdf")
  self.paperclip_model = f
  save
end



回答2:


Did you try tempfile = File.open("#{RAILS_ROOT}/tmp/myfile_#{Process.pid}",'w') ?


The correct syntax is tempfile = File.new("#{RAILS_ROOT}/tmp/myfile_#{Process.pid}",'w') (see comments)



来源:https://stackoverflow.com/questions/4356582/rails-using-tempfile-to-write-on-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!