Friday 11 January 2008

MERB: Rendering JPEG's from actions

While working on my MERB app, I wanted to pull an image from the database and render it inline as if it were a static jpg. I knew how to do this in Rails but not in MERB. It turns out to be really easy, although quite different from how it is done in Rails.

This blog post was very useful to figuring it out.

Let's suppose you have a database model Image and an Images controller and action 'show'. Firstly at the end of your merb_init.rb file, put the following line:
Merb.add_mime_type(:jpg, :to_jpg, %w[image/jpeg], {})

then in the controller add a provides parameter for jpg and

In your model add a method to_jpg like so.
def to_jpeg
data
end

Where data is the name of the column in your images table that holds the binary data.

Make sure you restart your server after all these changes.

Next your controller should look something like this:

class Image < Application
provides :xml, :js, :yaml, :jpg

def show
image = Image.find(params[:id])
render image
end
end


And thats it! If you go to /images/1.jpg (assuming RESTful routing...), the controller will retrieve the image with id 1 and MERB will call the to_jpg method on that object. It will then output that binary image data and send with the correct http header Content-Type parameter.