Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Tempfile - Modify file name?

I'm using Tempfile to store a generated PDF before uploading to a new destination.

    pdf_file = WickedPdf.new.pdf_from_string(msgbody)
    tempfile = Tempfile.new(['Bob', '.pdf'], Rails.root.join('public','pdf-test'))
    tempfile.binmode
    tempfile.write pdf_file
    tempfile.close

While this works fine, the resulting file names, eg- bob20140331-19260-1g6rzr1.pdf are not user friendly.

I understand that Tempfile creates a unique name and why, but I ultimately need to change the name to make it more intuitive/easier to digest for my users.

Is there a recommended way to do so? Even if its to simply remove the middle (19260)? Thanks for your time and assistance.

like image 333
user464180 Avatar asked Nov 11 '22 10:11

user464180


1 Answers

A Tempfile is used to create a temporary file with a unique file name, which will be cleaned up by the garbage collector or when the ruby interpreter exits.

Tempfiles behave like File objects, but I am not sure if you can rename files and if you can, if the automatic cleanup described above will still work. Additionally you might break the constraint of unique file names if you change the temporary file name manually.

I suggest creating an ordinary file and specify the entire name by yourself (the succ method can be helpful to prevent name clashes).

Another solution might be setting the file name during or after the upload process, you mentioned.

like image 113
Tsunamis Avatar answered Nov 26 '22 09:11

Tsunamis