Monday, March 8, 2010

DRY Design Docs in Action

‹prev | My Chain | next›

Now that I ostensibly have DRY design documents work in couch_docs, let's see if they actually work.

I have a bunch of CouchDB views for meal documents that look something like this:
 function (doc) {
if (doc['type'] == 'Meal' && doc['published']) {
emit(doc['date'], doc);
}
}
I can extract the conditional code into a callback library function:
function emit_meal(doc, callback) {
if (doc['type'] == 'Meal' && doc['published']) {
callback(doc);
}
}

emit_meal(doc, emit_callback);
If I save that in _design/__lib/emit_meal.js, I can use it with a // !code edit_meal.js macro:
function (doc) {
function emit_callback(doc) { emit(doc['date'], doc); }

// !code emit_meal.js
}
But how to test? The answer to that is easy. First, I replace every meal conditional map with the !code callback version. Then I run my extensive collection of Cucumber scenarios:
cucumber
...
39 scenarios (1 pending, 38 passed)
344 steps (1 pending, 343 passed)
1m16.055s
Nice!

It turns out to be a good thing that I replaced all of the conditionals. Until I did, I had not noticied that some conditions omitted the doc['published'] check. Already I am realizing advantages of DRYing up my views!

Before moving on, I would like to check that dumping design documents works in the presence of !code macros. I already know that dumping only design documents is working (with the -d switch). Yesterday, I believe that I got dumping working such that !code macros that had been evaluated were subsequently replaced with the original !code macro upon dump to the file system.

Once the newly DRY design documents are loaded, I verify that they are in place with futon:



Yup, I see my new emit_callback in there. So I dump to a temporary directory and cat the contents of one of my newly DRY maps:
cstrom@whitefall:~/tmp/dump$ couch-docs dump -d http://localhost:5984/eee
cstrom@whitefall:~/tmp/dump$ cat _design/meals/views/by_date/map.js
function (doc) {
function emit_callback(doc) { emit(doc['date'], doc); }

// !code emit_meal.js
}
Yup, it is back to being DRY. For good measure, I diff this directory with the original source code:
cstrom@whitefall:~/tmp/dump$ diff -rw _design /home/cstrom/repos/eee-code/couch/_design/
Only in _design: relax
Success! The only difference is the couchapp document (relax) that I had been playing with, but had not committed to the source code yet. Since it was on the server, but not in the original design document source, it should show up as a difference.

I believe that concludes the couch_docs 1.1 feature set. Time permitting, I will gem push it tomorrow.

Day #36

No comments:

Post a Comment