Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip save attachment

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
like image 664
astropanic Avatar asked Mar 24 '26 02:03

astropanic


1 Answers

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!

like image 99
Jakub Avatar answered Mar 26 '26 15:03

Jakub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!