ruby-on-rails - 回形针保存附件

标签 ruby-on-rails paperclip

有没有更好的方法通过 Paperlip 将一些字符串保存为附件,如制作一个 tmp 文件,将字符串放入其中,再次打开它并将其另存为附件?

像这样:

  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

最佳答案

实际上有一个更好的方法 - 你可以将它包装到 Paperclip 增强的 StringIO 中,你会立即得到一个伪上传的文件。您可以通过定义实例方法来自定义它,也可以像这样直接创建 StringIO 的子类

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

尽情享受吧!

关于ruby-on-rails - 回形针保存附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1199343/

相关文章:

ruby-on-rails - 通过回形针从 URL 保存图像

ruby-on-rails - 使用关联模型重命名图像 - Paperclip

ruby-on-rails - 如何使用 Globalize3 制作本地化的回形针附件?

ruby-on-rails - OSX 10.8升级后postgres无法连接服务器

ruby-on-rails - 在 Ruby 中编写具有动态背景颜色的 Excel 工作表

jquery - Twitter Bootstrap Scrollspy 在滚动时不起作用

ruby-on-rails - rails + 回形针 : Is a generic "Attachment" model a good idea?

ruby-on-rails - 什么是包含字母、无空格或特定长度数字的用户名的正则表达式?

ruby-on-rails - Ruby on rails : Remote Upload A File Using AJAX

heroku - Paperclip、Delayed Job、S3、Heroku - 用于延迟处理敏感上传文件的设计 : db or s3?