Tuesday, May 26, 2009

LambdaPeriodicalUpdater

Whenever I use Prototype's PeriodicalUpdater, I run up against an annoying limitation: the URL you give it to periodically update against is a string, not a function. However, if you're using RESTful or even just old-school id-centric Rails routes, hitting the exact same URL every time means you can't encode any information in the URL which might change over the course of the page view.

For instance, say you're writing a Twitter client. You want to track status IDs and only pull tweets older than a given status ID, since you can safely assume that anything earlier is already on your page. The easy way to do that looks like this:

http://localhost:3000/twitter/new_tweets_since/12345

But with PeriodicalUpdater, you can't ever change 12345 to 67890 (or whatever the most current status ID is). Your options then become either tracking on the server side what tweets the page has already seen, which is a nightmare; or downloading a whole batch of tweets, both good and bad, which you then have to filter through to determine whether or not you want to display them; or giving up and going home. These options all suck. Your one good option is to cut and paste the PeriodicalUpdater code and set it up to take a function instead of a string. Boom, suddenly all your problems are solved, the world is a happy place, and you put it on GitHub.

In terms of code changes per hour of stress averted, lambdas nearly always rock. This class for me today sent away loads of aggravation just by adding a pair of parentheses. I changed a variable name too, but that was strictly icing on the cake.