file_column image regeneration

August 11th, 2008

If you use file_column for some projects and find that you want to change the thumbnail sizes that you’ve been using for models, then hopefully this little bit of code can help.

Add this as a rake task and run it as rake "filecolumn:regenerate[Model, field]" RAILS_ENV=production where Model is the model you want to regenerate images for and field is the filecolumn field on the model. The task uses Rake arguments, so you’ll need Rake 0.8.

namespace :filecolumn do
  desc "Regenerate filecolumn images"
  task :regenerate, :model, :field, :needs => :environment do |task,args|
    if args.any?{|k,v| v.blank?}
      puts "Usage: #{task.name}[Model,field]"
    else
      klass, field = args.model.constantize, args.field

      klass.all.each do |obj|
        puts "Regenerating #{klass} #{obj.id}"
        next if obj.send(field).nil?
        state = obj.send("#{field}_state")
        state.instance_variable_set(:@just_uploaded, true)
        state.transform_with_magick
      end
    end
  end
end
The code essentially boils down to 2 lines…
  • setting @just_uploaded to true on the state object
  • calling the transform_with_magick method on the state object

2 Responses Follows

  1. Matt Todd says

    Hey, thanks for this task, just had to use this today. Appreciate sharing it!

  2. Matt Todd says

    One thing, I had to update magick_file_column.rb line 20 to call FileUtils.mkdir_p instead of just FIleUtils.mkdir so that it wouldn’t complain about an already existing folder when it tries to create the subfolder for the different sizes.


Your Response