Generating your own thumbnails with acts_as_attachment:
As per my blog post, here’s how to create your own thumbnails using acts_as_attachment.
Rick Olson’s acts_as_attachment plugin is the shit when it comes to handling file uploads in Rails, but it lacks the
:crop
option that the file_column plugin does.
If you’re looking for flickr-style square thumbnails you’ll have to do the thumbnail generation yourself.
Luckily for us Rick provides an
after_attachment_saved
callback which gets called when a photo gets saved. We can use this hook to generate our own thumbnails rather than using acts_as_attachment’s pre-baked
:thumbnails
option. The only gotcha is that the hook also gets called when the thumbnail itself is saved, so you have to check the
parent_id
before going ahead.
class Photo < ActiveRecord::Base
THUMBS = { :profile => 150, :medium => 75, :tiny => 25 }
belongs_to :person
acts_as_attachment :storage => :file_system,
:content_type => :image
validates_as_attachment
# We handle our own thumbnail generation
after_attachment_saved do |photo|
if photo.parent_id.nil?
THUMBS.each_pair do |file_name_suffix, size|
thumb = thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, photo.id)
resized_image = photo.crop_resized_image(size)
unless resized_image.nil?
thumb.attributes = {
:content_type => photo.content_type,
:filename => photo.thumbnail_name_for(file_name_suffix.to_s),
:attachment_data => resized_image
}
thumb.save!
end
end
end
end
def crop_resized_image(size)
thumb = nil
with_image do |img|
thumb = img.crop_resized(size, size)
end
thumb
end
end
