Search code examples
rubyfilepapercliprendertemporary-files

Can I have a File-instance with content without saving the file?


For paperclip I have a file that I add programmatically. The file is a generated PDF. So basically I don't need this file to be saved to my server's HDD. What I do now is the following:

@tempfile = Tempfile.open( ['','.pdf'], nil, 'wb', encoding: "ASCII-8BIT") do |file|
  file << render_to_string( pdf: "pdf_file.pdf", layout: "pdf", template: "projects/generatePDF" )
end

@export.pdf = File.open( @tempfile.path )     # Paperclip Attachment

These are three steps: Create, write, open. So I'm wondering if we can do this easier, something like the following would be great:

@export.pdf = File.new( render_to_string( pdf: "pdf_file.pdf", layout: "pdf", template: "projects/generatePDF" ) )

Solution

  • Try using a stringio - this is a subclass of IO that is backed by a string rather than a file.