Monday, May 11, 2009

Meal Upload

‹prev | My Chain | next›

To prepare for working with meals in my EEE Cooks replacement, I need to upload the old Rails meals into the new CouchDB store. Fortunately, I have already done this with recipes.

Just as I did with Recipe, I need to re-open the Meal class so that a few methods can be added to it:
class Meal < ActiveRecord::Base
# IDs - date suffices for a meal (we never do more than one meal per day)
def _id; date.to_s end

# For uploading meal images
def _attachments
{
self.image.filename =>
{
:data => Base64.encode64(File.open(self.image.full_filename).read).gsub(/\n/, ''),
:content_type => "image/jpeg"
}
}
end

# For the menu
def menu; menu_items.map(&:name) end

# To distinguish between meals, recipes, etc.
def type; self.class.to_s end
end
To include these methods in the JSON output:
>> m = Meal.first
=> #<Meal id: 15, title: "The Bestest Dinner Ever", summary: "...
>> json = m.to_json(:methods => [:_id, :menu, :type, :_attachments], :except => [:id, :image_old])
=> "{"type": "Meal",
"title": "The Bestest Dinner Ever",
"published": true,
"date": "2006/05/03",
"_id": "2006-05-03",
"serves": 4,
"_attachments": {"egg_dinner_7321.jpg": {"data": "/9j/4AAQSkZJRgABAQEASABIAAD...
Uploading the document to CouchDB is easily accomplished with a RestClient call:
>> RestClient.put "http://localhost:5984/eee/#{m._id}", json, :content_type => 'application/json'
=> "{"ok":true,"id":"2006-05-03","rev":"1-1328519176"}\n"
A quick check in Futon to make sure all is OK and I am all set:



For work over the next couple of days, I note the JSON structure in CouchDB:
{
"_id": "2006-05-03",
"_rev": "1-1328519176",
"type": "Meal",
"title": "The Bestest Dinner Ever",
"published": true,
"date": "2006/05/03",
"serves": 4,
"summary": " [kid:son1] was very excited about this meal. When he sat down to eat, he had in front of him pasta and cheese sticks. A thin slice of heaven for him. And this was before the sausage was put on the table. ",
"description": " The girls were quite pleased with the dinner as well. Especially once Robin gave some lettuce to [kid:daughter2]. ",
"author_id": null,
"menu": [
" [recipe:2006/05/03/eggs] ",
" [recipe:2003/11/25/caesar_salad Caesar Salad] (served topped with the fried eggs) ",
" Baked Macaroni with Sausage ",
" Mozzarella Sticks "
],
"_attachments": {
"egg_dinner_7321.jpg": {
"stub": true,
"content_type": "image/jpeg",
"length": 30411
}
}
}

No comments:

Post a Comment