Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Paperclip without a file, just with a string?

I have a rake file, that reads content via HTTP and I want to use Paperclip to store the loaded content on Amazon S3. It works fine when I provide a local file, but I would like to set the content as a string and set the content type manually.

The following does not work. No error is issued, the database entry is updated, but no file is created in S3:

p.attachment = "Test"
p.attachment_file_name = "test.txt"
p.attachment_content_type = "text/plain"
p.attachment_file_size = "Test".size
p.attachment_updated_at = Time.now
p.save

I guess I could write a temporary file with my content, but that would be a pretty inefficient solution.

like image 504
Jan Avatar asked Nov 03 '10 15:11

Jan


2 Answers

To avoid littering the filesystem with temp files, you can use StringIO as in:

p.attachment = StringIO.new(your_string)
like image 97
Leopd Avatar answered Oct 08 '22 19:10

Leopd


It's a bit late but I pulled it off by creating a Tempfile using ruby 1.9.2 rails 3.1

file = Tempfile.new( ["file_name", '.txt'] )
file.write( "my test string".force_encoding('utf-8') )
p.attachment = file
like image 29
Aaron Renoir Avatar answered Oct 08 '22 21:10

Aaron Renoir