Is it possible to set the cache extension dynamically?

I want to cache images I have in the database along with the html that is being put out. But the only way I have encountered to alter the cache extension from the default ".html" is to add ActionController::Base.page_cache_extension = ".jpg" to config/ environment.rb. Naturally, what I need is save the HTML as ".html" and the JPGs as ".jpg". Does anybody know how to do that? Thanks. -Sebastian

I want to cache images I have in the database along with the html that is being put out. But the only way I have encountered to alter the cache extension from the default ".html" is to add ActionController::Base.page_cache_extension = ".jpg" to config/ environment.rb. Naturally, what I need is save the HTML as ".html" and the JPGs as ".jpg". Does anybody know how to do that?

What version of Rails?

In 1.2 you can set a route like this:

map.photo 'cache/photo/:id.jpg', :controller => 'home', :action => 'photo'

Which would result in cache/photo/123.jpg being cached to disk.

In 1.16 you can do this:

map.photo 'cache/photo/:id/image.jpg', :controller => 'home', :action => 'photo'

Which would result in cache/photo/123/image.jpg being cached to disk.

The key is to use a named route so in your views you can use photo_url(:id => 123) to generate the right url.

-philip

Philip, is it possible to use a sweeper to clean up these kinds of cached images? If so, this might be something that’d eliminate a good bit of wacky code I’ve got in one of my models. Or at least move it out to a Sweeper where it makes a little more sense.

RSL

Philip, is it possible to use a sweeper to clean up these kinds of cached images? If so, this might be something that'd eliminate a good bit of wacky code I've got in one of my models. Or at least move it out to a Sweeper where it makes a little more sense.

Don't know... never tried it :slight_smile: In my case I don't want them to expire though so didn't look into it.

That's definitely a lot more flexible. It still stops short of being able to determine the MIME type and save the cache file with the according extension. But it is already much better. Thanks a lot!

-sebastian

Well, it took me a while to get around to test it, but (of course, I might say) what Phillip suggested is much more flexible than I first thought:

You can declare your route like this: map.file 'serve_file/:id.:ext'

And then send your file like this: file_url(:action => 'serve_file', :id => target.id, :ext => target.extension)

Exactly what I needed! Thanks again.

Sebastian