2009-07-29 121 views
3

有沒有更好的方式來保存一些字符串作爲附件通過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 
+1

你爲什麼要這麼做? – Lichtamberg 2009-07-29 13:35:57

回答

0

回形針店文件沿着你的模型 - 這是它已經被寫入做的,所以我想簡單的答案是「不」。

如果您在回形針源文件中查看attachment.rb,您會看到一種名爲def assign uploaded_file的方法。如果你看看這個方法的實現,你可以看到它希望上傳的文件對象有一個定義的特定方法。

您可以創建自己的類,它遵循與Paperclip所期望的相同的界面,但說實話,您保存文件並將其分配給Paperclip的解決方案可能是最簡單的方法。

4

實際上有一個更好的方法 - 你可以將它包裝到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 

享受!

+0

這是如何與ActionMailer一起使用的? – TheExit 2010-12-05 17:16:12