REBOL notes: WITH convention
March 15th, 2009I will try to post small tidbits of nice and hopefully interesting practices that I find I can do with rebol. Nothing revolutionary or big.. just nice..
One of them is the with convention/pattern whatever. I saw something very similar before in Factor. Not that many languages can do this, especially not this elegantly.
Using SQLite
Rebol has a SQLite binding provided by Dobeash Software. I am making a web-app where each user has his own sqlite database (I have my reasons). This could be an example of two simple functions:
get-user-notes: does [
CONNECT get-user-db
result: SQL "select * from notes;"
DISCONNECT
result
]
get-note: func [ id ] [
CONNECT get-user-db
result: SQL [ "select * from notes where id = ?;" id ] ]
DISCONNECT
result
]
note: REBOL is case insensitive so those upper case words can be lower case ; get-user-db returns path to sqlite db of the current user ; the result of last expression is returned (result word here)
So it seems we have a little “state machine” here and a required! pre and post action, and we have to store result value because we need to disconnect after the query. Quite clumsy to write connect and take care to disconnect each time. So let’s factor the noise out! As I said, Factor used this, and it’s also trivial to make in rebol. We will make our custom func with-user-db
with-user-db: func [ code ] [
CONNECT get-user-db
result: do code
DISCONNECT
result
]
Now all functions that deal with database become very clean and stateless.
get-user-notes: does [ with-user-db [ SQL "select * from notes;" ] ] get-note: func [ id ] [ with-user-db [ SQL [ "select * from notes where id = ?;" id ] ]
Debugging JSON responses
Another example where with-* convention got handy was right now. I was writing a function that generates and returns JSON to browser. Something wasn’t working so I wanted to quickly see what value two words are holding by inserting ?? (prints name of word and prettyprinted value).
...code... ?? data ?? columns ...code...
with some random strings in response JSON response wasn’t valid so the webapp client stopped working. This can be quickly solved by wrapping those debug strings with JavaScript comments.
/* sobe random debug stuff */{propper: "JSON"}
So I created a with one-liner
with-js-comment: func [ print "/*" do code print "*/" ]
And now I can debug without breaking the client by using:
...code... with-js-comment [ ?? data ?? columns ] ...code...
—
Of course these two are not the only uses of with convention and my concrete SQLite example was more complex (optionally returning column names also, more connect setup) so with-user-db removed even more noise. I just wanted to illustrate some of the flexibility that the language’s core design casually provides.

![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=bf9f044e-313f-4c69-acb2-8fb0daa89283)