开发者

Styles in Paperclip only if it's an image [rails]

I'm using paperclip to upload all sorts of files (text documents, binaries, images).

I'd like to put this in my model:

has_attached_file :attachment,开发者_Python百科 :styles => { :medium => "300x300>", :thumb => "100x100>" }

but it has to perform the styles only if it's an image. I tried adding

if :attachment_content_type =~ /^image/

but it didn't work.


You can use before_<attachment>_post_process callback to halt thumbnail generation for non-images. If you return false in callback, there will be no attempts to use styles.

See "Events" section in 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 


May be you need something like this:

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

And define method in your model:

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


You can use on your model

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜