This repository was archived by the owner on Jul 13, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
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.
Asset.rb
# 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)$}
end
private
def resize_images
return false unless image?
end_asset.html.erb
<% if asset.image? %>
<%= image_tag asset.download_url(:thumb) %>
<% else %>
<%= asset.upload_file_name %>
<% end %>