Ruby-on-rails – write stream to paperclip


I want to store received email attachment with usage of paperclip. From email I get part.body and I have no idea how to put it to paperclip'ed model. For now I create temporary file and write port.body to it, store this file to paperclip, and delete file. Here is how I do it with temporary file:

    l_file =, "w+b", 0644)
    oAsset =
        :email_id =>, 
        :asset => l_file, 
        :header => h, 
        :original_file_name => o, 
        :hash => h)

:asset is my 'has_attached_file' field. Is there a way to omit file creation and to do something like: :asset => part.body in ?

Best Solution

This is how I would do it, assuming your using the mail gem to read the email. you'll need the whole email 'part', not just part.body

file = #mimic a real upload file
  file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs
  file.original_filename = part.filename #assign filename in way that paperclip likes
  file.content_type = part.mime_type # you could set this manually aswell if needed e.g 'application/pdf'

now just use the file object to save to the Paperclip association.

a = 
a.asset = file!

Hope this helps.

Related Question