2010-05-27 119 views
8

我使用回形针上传各种文件(文本文档,二进制文件,图像)。回形针的样式只有当它是一个图像[rails]

我希望把这个在我的模型:

has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" } 

,但它必须执行的样式只有如果它是一个形象。我试图加入

if :attachment_content_type =~ /^image/ 

但它没有工作。

回答

15

您可以使用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 
3

参见 “事件” 部分可能是你需要的东西是这样的:

:styles => lambda { |attachment| 
    !attachment.instance.image? ? {} : {:thumb => "80x24", :preview => "800x600>"} 
} 

而在你的模型中定义的方法:

def image? 
    attachment.content_type.index("image/") == 0 
end 
1

您可以使用在你的模型上

`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"`