Sunday, July 22, 2007

Little Rails Image Caching Caveat

If you want to serve a jpg from a database with a url like:

whatever.com/jpegs/heres_a_jpeg/12345

...you can do that, sending jpegs from jpegs_controller.rb with send_data, but if you then do something like:

caches_page :heres_a_jpeg

...then Rails will assume you're serving HTML instead of jpegs, because it doesn't know any better, since you haven't told it.

In my case, I didn't notice at first. What I did notice is that my jpegs started looking terrible. I did a manual export in the Rails console with something like:

File.open("picture.jpg", "w") {|pic| pic << Image.find(:first).data}

...and then from the OS X Unix command line:

open picture.jpg

...and the pic was gorgeous.

What was happening is that when Rails cached my images with .html extensions, it corrupted the images. Some subtle snafu in the MIME type translation process, maybe.

Fortunately all this is easy to fix: just set your routes to assume a .jpg extension from that heres_a_jpeg action, and make sure your URLs pointing to that action all end in .jpg. Then Rails will cache it properly and no problem at all.

1 comment:

  1. You can set the content_type in send_data if i am not wrong??
    Thanks for the info i wanted to cache something like this and this helped know which type of caching to use

    ReplyDelete

Note: Only a member of this blog may post a comment.