views:

420

answers:

2

Is there a better way to save some string as an attachment via Paperlip as making a tmp file, putting the string into it, opening it again and saving it as an attachment ?

Like this :

  def save_string data
    tmp_file = "/some/path"
    File.open(tmp_file,'w') do |f|
      f.write(data)
    end

    File.open(tmp_file,'r') do |f|
      ceneo_xml = f
      save!
    end
  end
A: 

Paperclip stores files alongside your models -- this is what it has been written to do, so I think the short answer is "no".

If you look in attachment.rb in the Paperclip source you'll see a method called def assign uploaded_file. If you look at the implementation of this method you can see that it expects the uploaded file object to have a certain methods defined on it.

You could create your own class which followed the same interface as Paperclip expects, but to be honest your solution of saving a file and assigning that to Paperclip is probably the easiest approach.

Olly
A: 

There is actually a better way - you can wrap it to StringIO which Paperclip enhances and you will get a pseudo uploaded file in no time. You can customize it by defining instance methods or directly create a subclass of StringIO like this

class InvoiceAttachment < StringIO
 def initialize(invoice, content)
   @invoice = invoice
   super(content)
 end

 def original_filename
   from = @invoice.from
   to = @invoice.to
   date = @invoice.created_at.strftime('%B-%Y').downcase 
   "invoice_#{date}_from_#{from}_to_#{to}.pdf"
 end

 def content_type
   'application/pdf'
 end
end

Enjoy!

Jakub