Friday, April 3, 2009

Render CouchDB Images Via Sinatra

‹prev | My Chain | next›

Having finished the recipe details last night, I realized that I had no way of serving up the images stored in the CouchDB database. Something of a frightening realization, but it turns out to be as simple as:
get '/images/:permalink/:image' do
content_type 'image/jpeg'
RestClient.get "#{@@db}/#{params[:permalink]}/#{params[:image]}"
end
The content_type line specifies the content type as a JPEG image.

The RestClient.get retrieves the document from the CouchDB database and serves up the output to the requesting client. The :permalink parameter is the URL of the recipe document itself. Accessing an attachment to that document is as simple as adding a slash and the name of the attachment. If the recipe's ID is 2008-07-21-spinach and the image filename is spinach_pie_0004.jpg, then I can use the Sinatra resource to access the image at http://localhost:4567/images/2008-07-21-spinach/spinach_pie_0004.jpg:



Next up: deleting this and redoing it with a spec—mostly to handle not found errors.

No comments:

Post a Comment