2017-03-06 62 views
0

我在文档模型上使用Carrierwave。如何将主机添加到Carrierwave网址?

class Document 
    mount_uploader :file, DocumentUploader 
end 

,我试图用文档发送电子邮件作为附件

class DocumentMailer 
    def distribute(recipient, document) 
    filename = document.file.file.original_filename 
    attachments[ filename ] = File.read(document.file.url) 
    mail( 
     to: receipient.email, 
     subject: "Document attached" 
    ) 
    end 
end 

在测试中,梅勒是引发错误

Errno::ENOENT: 
     No such file or directory @ rb_sysopen - /uploads/document/file/2/my_attachment.jpg 

我可以在测试套件解决这个错误通过在DocumentMailer中调用path而不是url,它返回完整的文件系统路径

attachments[ filename ] = File.read(document.file.path) 
# /Users/AHH/code/myapp/tmp/uploads/document/file/2/my_attachment.jpg 

但是,这会导致该方法在生产中失败。 Carrierwave正在使用fog来存储S3上的文件,因此我需要完整的url将附件分配给DocumentMailer。

为什么使用file.url时测试失败?我认为这是因为该网址没有主机。那么如何确保Carrierwave在测试环境中将主机应用于file.url

回答

0

由于url实际上是生产中的URL,可能是S3主机,但是在本地它是通向文件的路径,因此这是开发/测试与生产中存储文件的方式的副作用,相对于您指定要上载的任何地方而言。不幸的是,似乎CarrierWave没有一种优雅的处理方式,至少就我所见,所以我最终在我们的帮手中做了这样的事情:

config.before do 
    allow_any_instance_of(DocumentUploader).to receive(:url) do |uploader| 
    uploader.path 
    end 
end