我正在使用Paperclip来上传各种文件(文本文档、二进制文件、图像)。
我想把它放在我的模型中:
has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }
但是它只有在图片的情况下才需要执行样式。我尝试添加,但这会导致HTML代码错误。
if :attachment_content_type =~ /^image/
但是它没有起作用。
我正在使用Paperclip来上传各种文件(文本文档、二进制文件、图像)。
我想把它放在我的模型中:
has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }
if :attachment_content_type =~ /^image/
before_<attachment>_post_process
回调函数来停止非图片的缩略图生成。如果在回调函数中返回false
,则不会尝试使用样式。 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"`