序列化Tempfile以在后台工作程序中发送

时间:2016-06-03 14:16:46

标签: ruby-on-rails ruby

我的想法是尝试将TempFile转换为字符串,然后将该字符串转换回TempFile。使用ruby有更简单的方法吗?

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

string_file = file.to_s
new_file = file.to_file 

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?这对我来说是一个基本的文本文件。

<强>红宝石

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

<强>输出

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