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
I guess I could write a temporary file with my content, but that would be a pretty inefficient solution.
No, you have to create a file with your string.
Just look at the Paperclip source code : https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/attachment.rb#L77 and https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/iostream.rb#L5
when you assign something using my_model.attachment=, Paperclip wants a file object.
To avoid littering the filesystem with temp files, you can use
StringIO as in:
p.attachment = StringIO.new(your_string)
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
For both paperclip and carierwave I end up creating a class like this. It has both methods needed to mock a file upload which they like to see.
class FakeFileIO < StringIO attr_reader :original_filename attr_reader :path def initialize(filename, content) super(content) @original_filename = File.basename(filename) @path = File.path(filename) end end
Works like a dream
Similar to Aarons but with the proper block method as suggested by Ruby:
...one should always call unlink or close in an ensure block.
file = Tempfile.new('test.txt') begin file.write( "Test" ) p.attachment = file p.save # Whatever else you might need to do with the TempFile. ensure file.close file.unlink # Deletes the temp file. end