Ruby-on-rails – write stream to paperclip

paperclipruby-on-railsstream

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 = File.open(l_path, "w+b", 0644)
    l_file.write(part.body)
    oAsset = Asset.new(
        :email_id => email.id, 
        :asset => l_file, 
        :header => h, 
        :original_file_name => o, 
        :hash => h)
    oAsset.save
    l_file.close
    File.delete(l_path)

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

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 = StringIO.new(part.body) #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 = Asset.new 
a.asset = file
a.save!

Hope this helps.

Related Question