Opposite of Cache Sweeper?

I'm looking for an acceptable way to cache images when they are
inserted into the database. Essentially an observer for the model,
however, i feel that this is not a concern of the model.

Currently i'm using the caches_action method to cache these images.
This only caches when the request is made for the image though.
Processing these images/pdf's with Rmagick takes some time so i'd
like for the image to be cached before it is requested.

Any suggestions?

If you want them on disk (not in the database) then why are you not just storing them in the file system and then referencing them in the db? Do all the work on the upload (rmagick / whatever).

But furthermore to you question:

I would argue that caching them to disk upon insertion is the job of the model (after_save) but if that’s not clean enough for you then you should investigate active record observers, or some sort of batch operation that runs separately.

Thanks Brian, I chose not to store the images on disk because it
limits the application to retrieve images from one specific server.
Using MySQL to store images i could potentially replicate and
distribute traffic amongst different servers. I wanted to leave my
options open.

Thank you for your suggestion. However, from what i know about
observers they are very close to the model. I could be wrong. Do you
know a good way to invoke an action in a controller from a rake task?

Explain what you’re doing first.

If you want to cache the stuff to disk to avoid constant processing, then write them to disk and reference in the db. Scaling out to multiple machines is a non-issue - just mount the file system on multiple machines and all is good. Or investigate Amazon S3 for your storage. If you’ve used attachment_fu, you can easily switch from filestore to database store to s3 without much effort.

Why wouldn’t you want to do this close to the model? Why would you want a controller action to be invoked via a rake task?

My implementation would be this:

class Attachment > ActiveRecord::Base

after_create :cache_to_disk

def cache_to_disk
# code that writes to some folder specified by a configuration value
end

end

When things are saved, you cache to disk automatically.

When you need to force a rewrite of the files on your file system, use Rake

desc “cache files”
task :write_attachments => :environment do
attachments = Attachment.find(:all)
attachments.each{|a.cache_to_disk}
end

Personally, I would not store files in the database at all. It seems like a good idea at first but files should be served by the file server. You can write code to replicate your filesystem across servers, you could use a shared folder or an nfs mount, or you could use S3 instead of doing something like this.

Just my .02, and feel free to argue, just hoping to help you find the best solution.

Good luck!