Friday, September 5, 2008

Rake: Update or create images generated by attachment_fu

Did you upload a bunch of images and find out that the new layout needs a new size of the photos, and you didn't specify this in the has_attachment line of your model?

This happened to me, and I wanted an easy to way update all images in the database. I didn't test this with millions of records or anything, but if you want to fix this up please leave a comment.

Notes:
  • To use, simply edit has_attachment line with the new thumbnail sizes you want.
  • IdeaImage is the model that I want to update
  • parentless is a named_scope that gets only the IdeaImages whose parent_id's are null.

namespace :images do
desc "Updates all the thumbnails of idea_images based on the thumbnails hash in the model"
task(:update_idea_images => :environment) do
IdeaImage.parentless.each do |i|
#destroy the thumbnails first
i.thumbnails.each { |thumbnail| thumbnail.destroy } if i.thumbnailable?
#then recreate the thumbnails
i.attachment_options[:thumbnails].each { |suffix, size| i.create_or_update_thumbnail(i.create_temp_file, suffix, *size) }
end
end
end

No comments: