How to use attachment_fu in a rake task (i.e., without using a form)

We’re launching a new Facebook app soon at OnMyList, and we need to pre-populate hundreds of celebrity images, so instead of doing it manually I wrote a cute little rake task to do them all. Took me a little while to figure this out, the trick is to do a class_eval to add the required fields to make attachment_fu happy. This works pretty sweet, the images are resized and uploaded to Amazon S3.

Thought I’ll blog it hoping someone out there will find this useful. 🙂

desc 'adding celebs'
task :add_celebs => :environment do
  dir = '/tmp/celeb_images'
  Dir.foreach(dir) do |img|
    path = File.join(dir, img)
    if File.file?(path)
      f = File.new(path, "r")
      (class < < f; self; end).class_eval do
      alias local_path path
        define_method(:original_filename) {img}
        define_method(:content_type) {"image/jpeg"}
        define_method(:size) { File.size(path) }
      end
      u = User.new
      u.celeb_name = File.basename(img, '.jpg').titleize
      u.picture = Picture.new
      u.picture.uploaded_data = f
      u.save!
      p "added user #{u.celeb_name}"
    end
  end
end

Technorati Tags: , , , , ,

One thought on “How to use attachment_fu in a rake task (i.e., without using a form)

  1. Joshua Pinter

    Thanks man! You saved me a whole lotta time.

    For what it's worth, I had to replace "(class < < f; self; end).class_eval" to just "f.class_eval" to get it to work.

    I'm on Ruby 1.8.7 over here.

    Thanks again.

    Reply

Leave a Reply