Ctpelnar1988 Ctpelnar1988 - 5 months ago 25
Ruby Question

Serialize Tempfile to send in background-worker

My idea is to try to convert a TempFile into a string and then convert that string back into a TempFile. Is there an easier way to do this with ruby?

file = #<File:/var/folders/b6/c3fypxm50b75hszctcgr8brm0000gn/T/RackMultipart20160603-8771-rehwdq.pdf>

string_file = file.to_s
new_file = file.to_file

Answer

What about something like this? This is working with a basic text file for me.

Ruby

require 'json/add/struct'

Struct.new("FileObject", :name, :content)

file = File.open('/tmp/file.txt',mode='r')
file_name = file.path.split('/').last
file_contents = file.read
file_obj = Struct::FileObject.new(file_name,file_contents)
file_json = file_obj.to_json
file.close

## Convert back to file
new_file_obj = JSON.parse(file_json, :create_additions => true)
new_file = File.open('/tmp/saved_' + new_file_obj.name,'w+')
new_file.write(new_file_obj.content)
new_file.close

Output

2.3.0 :001 > require 'json/add/struct'
 => true 
2.3.0 :002 > Struct.new("FileObject", :name, :content)
 => Struct::FileObject 
2.3.0 :003 > file = File.open('/tmp/file.txt',mode='r')
 => #<File:/tmp/file.txt> 
2.3.0 :004 > file_name = file.path.split('/').last
 => "file.txt" 
2.3.0 :005 > file_contents = file.read
 => "some file content\nblah\n\nblah blah\n" 
2.3.0 :006 > file_obj = Struct::FileObject.new(file_name,file_contents)
 => #<struct Struct::FileObject name="file.txt", content="some file content\nblah\n\nblah blah\n"> 
2.3.0 :007 > file_json = file_obj.to_json
 => "{\"json_class\":\"Struct::FileObject\",\"v\":[\"file.txt\",\"some file content\\nblah\\n\\nblah blah\\n\"]}" 
2.3.0 :008 > file.close
 => nil 
2.3.0 :009 > new_file_obj = JSON.parse(file_json, :create_additions => true)
 => #<struct Struct::FileObject name="file.txt", content="some file content\nblah\n\nblah blah\n"> 
2.3.0 :010 > new_file = File.open('/tmp/saved_' + new_file_obj.name,'w+')
 => #<File:/tmp/saved_file.txt> 
2.3.0 :011 > new_file.write(new_file_obj.content)
 => 34 
2.3.0 :012 > new_file.close
 => nil 
Comments