我使用回形針上傳各種文件(文本文檔,二進制文件,圖像)。回形針的樣式只有當它是一個圖像[rails]
我希望把這個在我的模型:
has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }
,但它必須執行的樣式只有如果它是一個形象。我試圖加入
if :attachment_content_type =~ /^image/
但它沒有工作。
我使用回形針上傳各種文件(文本文檔,二進制文件,圖像)。回形針的樣式只有當它是一個圖像[rails]
我希望把這個在我的模型:
has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }
,但它必須執行的樣式只有如果它是一個形象。我試圖加入
if :attachment_content_type =~ /^image/
但它沒有工作。
您可以使用before_<attachment>_post_process
回調來暫停非圖像的縮略圖生成。如果您在回叫中返回false
,則不會嘗試使用樣式。在docs
before_attachment_post_process :allow_only_images
def allow_only_images
if !(attachment.content_type =~ %r{^(image|(x-)?application)/(x-png|pjpeg|jpeg|jpg|png|gif)$})
return false
end
end
參見 「事件」 部分可能是你需要的東西是這樣的:
:styles => lambda { |attachment|
!attachment.instance.image? ? {} : {:thumb => "80x24", :preview => "800x600>"}
}
而在你的模型中定義的方法:
def image?
attachment.content_type.index("image/") == 0
end
您可以使用在你的模型上
`has_attached_file :avatar,
:styles => lambda { |a| if a.content_type =~ %r{^(image|(x-)?application)/(x-png|pjpeg|jpeg|jpg|png|gif)$}
{
:thumb => "100x100#",
:medium => "300x300>",
}
else
Hash.new
end
},:default_url => "/missing.png"`