Conditionally resizing images

uberllama edited this page Apr 18, 2012 · 1 revision

A common case is to have an asset model that accepts multiple file types. In this case, you only want to apply resize operations if the uploaded file is an image.


# Table name: assets
#  id                  :integer(4)      not null, primary key
#  upload_file_name    :string(255)     not null
#  upload_content_type :string(255)
#  upload_file_size    :integer(4)      not null
#  upload_updated_at   :datetime

has_attached_file :upload, :styles => {:thumb => '100x100#'}
before_post_process :resize_images

# Helper method to determine whether or not an attachment is an image.
def image?
  upload_content_type =~ %r{^(image|(x-)?application)/(bmp|gif|jpeg|jpg|pjpeg|png|x-png)$}


def resize_images
  return false unless image?


<% if asset.image? %>
  <%= image_tag asset.download_url(:thumb) %>
<% else %>
  <%= asset.upload_file_name %>
<% end %>