Recursive templates with UnderscoreJS

I was working on a BackboneJS project recently that was using UnderscoreJS for templating and started wondering if its possible to invoke UnderscoreJS recursively.

At face value, the _.template function simply takes a template string and converts it to a first class Javascript function so I figured it would be possible. Out of curiosity, I decided to take a look at how the _. function is actually implemented:

Not any real surprises there – it basically does a series of string replaces on the template you pass in to interpolate any variables you want outputted, converts blocks you want evaluated to regular Javascript, and then injects the object you passed in into the local scope.

Then, the “magic” happens at “var render = new Function(settings.variable || ‘obj’, ‘_’, source);” where a new function is created with a “print” function locally defined and your template converted to a Javascript function.

Here is the “source” string that is passed into “new Function”:

That is the dynamic function generated for the following template:

Since its looking for the “template” function in the global scope it looks like everything should work fine. To test it, I decide to take the Fibonacci sequence and generate boxes for each of the numbers in the sequence up to some N.

Theres a live demo running at http://twitlabs.net/us/ and a Gist of the code is replicated below:

Just for fun, you can also change how the boxes are arranged by toggling between “Stacked” and “Cascaded”.

Anyway, fair warning – I imagine there are some performance implications regarding doing this as well as computational limits. You could potentially cause a stack overflow by consuming your entire stack via the recursion.

As always, questions, comments, concerns welcome!

BackboneJS: JSON over REST

We’ve recently started using BackboneJS on a couple of projects to help create more responsive UIs and avoid having to deal with a tangled mess of jQuery callbacks, ad-hoc Javascript templating, and difficult code re-use. On the whole, I’ve been impressed with Backbone and I think it’ll make a valuable asset in our toolbox.

Anyway, one of the core concepts of Backbone is that client side models will be automatically synced with their server side counterparts via RESTful AJAX calls. Stripping away the buzzword bingo, what that means is that when a Backbone model is created in the UI a AJAX POST request is initiated to create that model, updates trigger a PUT, and destroying a model will cause a DELETE.

Conceptually, this system makes a lot of sense and it fits nicely with how data is structured in most apps. Unfortunately, it falls apart when there isn’t a one to one correspondence between frontend Backbone models and your backend persistence layer.

For example, say on the frontend you wanted to allow a user to enter and edit the various languages she spoke. Naturally, you could define a Backbone “Language” model, managed by a “LanguageList” Collection, and finally drawn with a “LanguageView” View. This would work great but unfortunately on the backend you’re storing the list of languages the user speaks in a single row – say as a CSV list for arguments sake. At this point, you’d be stuck because Backbone would be pushing AJAX requests per model and your backend would have no way to combine the languages into a CSV list.

In this instance it seems like you really want “JSON over REST”, in the sense that you want to push update events for several models on a single request. The Backbone FAQ mentions this technique but unfortunately doesn’t elaborate on specifically how to achieve this behavior.

Batch operations on Models are common, but often best handled differently depending on your server-side setup. Some folks don’t mind making individual Ajax requests. Others create explicit resources for RESTful batch operations: /notes/batch/destroy?ids=1,2,3,4. Others tunnel REST over JSON, with the creation of “changeset” requests:

Google’ing around I stumbled across this StackOverflow answer – http://stackoverflow.com/questions/11298152/how-to-do-batch-operations-in-backbone-js-via-tunneling-rest-over-json which seems to have been removed. The answer basically suggested embedding a Collection within a Model so that Backbone effectively passed a JSON array to your REST endpoint.

Unfortunately, the answer didn’t provide a concrete example either so here is a stripped down version of what I ended up using.

Basically, “Language” is the “real” model which is managed by the “LanguageList” collection. Then, “LanguageCollection” is the container model which holds a single “LanguageList” collection and is subsequently managed by the “LanguageCollectionList”.

If you look through the code, basically the Views are bound to events on ‘LanguagesCollection.at(0).get(“languages”)’ which is a LanguageList object.

The other thing to note is that Language.destroy() function is updated to not make an AJAX DELETE call but instead trigger a save on the collection.

Also, LanguageCollection.parse() is defined as an empty function because ‘LanguagesCollection.at(0).get(“languages”)’ needs to remain a Backbone object and not be converted into the regular JSON which would come back from the server. The caveat here is that if you need to set an ID after a POST, you’ll need to update parse() to process the JSON and then update the corresponding models within the collection.

Anyway, I’m still a Backbone novice so any input or insight is more than welcome. I’d also love to know if theres a more straightforward way to address this. A couple of posts mentioned overriding Backbone.sync but that wasn’t feasible for me because I had other Backbone models on the page which needed to update using the regular REST pattern.

Update 7/20/2012

As pointed out by Aria below, it’s actually possible to override the “sync” method per model to achieve this JSON over REST behavior. Overall, its probably a cleaner solution since it avoids introducing the complexity of collections contained in models simply to get the JSON over REST behavior.

Here’s an example implementation of a sync function that produces the desired results:

NOTE: Almost all of that code is copied directly out of Backbone.js, the exception is the following block which collects up all the models in the current model’s collection and then adds it into the “data” field:

Happy Backbone’ing!

Use Exim and pipes to replicate MailGun routes

Over the last month or so I’ve been working with a friend of mine on a little side project (more on that later). During the course of the project, we ended up using Mailgun to receive email which was then passed to a PHP script using Mailgun routes.

Mailgun was pretty easy to setup and things were great but unfortunately in the last day or so our free app started creeping over the 200 message/day limit on the Mailgun free tier. Since the app is currently free, we couldn’t really justify paying the $19/mon minimum for the first Mailgun tier so I started exploring self-hosted options.

After a big of Googling, the first thing that caught my eye was the LamsonProject. From my understanding, Lamson basically provides a SMTP server which binds to a MVC application framework. After checking out the docs and the code it seemed like Lamson would allow you to build a RESTful application that responded to SMTP messages instead of HTTP requests. It certainly seems like a cool project but seemed like a bit overkill for what I needed to do.

Going further down the rabbit hole, I found out that the Exim allows messages to be delivered to a regular *nix process via a pipe and that the configuration was supposedly relatively straightforward under Ubuntu. Given that, I decided to give it a shot, it turned out to be relatively easy to setup but here is a quick rundown.

Step 1: Setup Exim

By default, Ubuntu systems are configured with sendmail and only setup to receive local mail. You’ll need to remove sendmail, install Exim, and then configure it.

To do this you’ll roughly need to run the following:

sudo apt-get remove sendmail
# for some reason the dependencies aren't being installed correctly
# see http://ubuntuforums.org/showthread.php?p=10411454
sudo apt-get install exim4-base exim4-config
sudo apt-get install exim4
sudo dpkg-reconfigure exim4-config

Next, follow the guide on https://help.ubuntu.com/8.04/installation-guide/hppa/mail-setup.html to configure Exim.

Step 2: Configure Pipes and Aliases

Per https://answers.launchpad.net/ubuntu/+source/mailman/+question/120447 it turns out something isn’t enabled in the default Ubuntu configuration of Exim. To solve this, I added the following

.ifndef SYSTEM_ALIASES_PIPE_TRANSPORT
SYSTEM_ALIASES_PIPE_TRANSPORT = address_pipe
SYSTEM_ALIASES_USER = Debian-exim
SYSTEM_ALIASES_GROUP = daemon
.endif

Into the bottom of /etc/exim4/conf.d/transport/30_exim4-config_address_pipe

After you edit an Exim setting, you’ll need to always run the following for the settings to take effect:

sudo update-exim4.conf.template -r
sudo update-exim4.conf
udo service exim4 restart

Next, you’ll need to enable the catch-all router configuration. This was surprisingly difficult to track down how to do:

Per, http://pontus.ullgren.com/view/Setting_SMTP_server_development_test_server_running_Ubuntu you need to create a file at /etc/exim4/conf.d/router/950_exim4-config_catchall containing

catch_all:
   debug_print = "R: catch_all for $local_part@$domain"
   driver = redirect
   data = ${lookup{*}lsearch{/etc/aliases}}
   # NOTE: I added this line for the catch all pipes to work
   pipe_transport = address_pipe

Finally, add a catch-all alias that pipes to a script to your /etc/aliases file. Mine looks like:

*: "|/home/ubuntu/exim4.php"

Step 2: The PHP script

I did this with PHP since my original Mailgun script was in PHP but anything should work. Key notes, the script needs to be accessible AND executable by the Exim user. Also, you’ll need the appropriate shebang to make the script work without a named interpreter.

Your script is going to receive raw SMTP email so you’ll need to parse that out to do anything meaningful with it. Thankfully there are plenty of libraries to do this. I ended up using MailParse along with PHP MimeMail Parse to abstract the nitty gritty into some cleaner object oriented code.

The part of my script that accepts and parses the email looks like:

From there, you’d be free to do anything you wanted with $msgInfo, just like on the receiving end of a Mailgun route.

Anyway, as always let me know if you have any feedback, questions, or comments.

Toggle non-consecutive checkboxes with jQuery UI

You’re all probably familiar with the UI convention of allowing users to select ALL or NONE for a list of checkboxes (like in Gmail). Recently I was working on a project that had a large table full of checkboxes (imagine a 10×10 grid) where the user would need to toggle some but not all of the checkboxes in a given row. And to make matters more complex, they would need to toggle groups of non-consecutive checkboxes (say 15, skip 10, 5, etc.). I threw on the thinking cap but couldn’t think of any similar interactions I’d seen and couldn’t think of a particularly good way to achieve this.

Enter jQuery UI. I happened to stumble across the jQuery UI Selectable documentation and realized it would provide a good UI experience to toggle some but not all of the checkboxes. The code to implement this is surprisingly simple:

Note: You don’t actually need the div container – that was just for JSFiddle.

And then the Javascript (jQuery + jQuery UI):

You can check out a live demo at http://jsfiddle.net/whMyQ/3/

As always, questions and comments are welcome!

Facebook: How-to force users to LIKE page

With Facebook’s move to deprecate FBML for tabs the documentation around how to make a “please Like! before…” has become much more choppy and inconsistent. Anyway, I recently found myself in a position where I needed to make this happen so here goes.

With in-line FBML deprecated, the only way to accomplish this without using a third party branded solution is to create a Facebook iframe app. Here are the steps you need to take to get something up using PHP and the Facebook PHP SDK.

1. Create a new Facebook Application at https://developers.facebook.com/apps

2. Configure your new Facebook App the enable “Website” and “Page Tab”. You’ll need to enter a valid URL for the following fields:

  • Site URL
  • Page Tab URL
  • Secure Page Tab URL

You’ll also want to use a HTTPs URL since Facebook sessions default to HTTPs by default and your iframe will be marked insecure if its over vanilla HTTP. For this walk through, lets assume were using https://www.setfive.com/fb/index.php? as the URL.

3. Now, you’ll want to add your new App to a Facebook Page. The easiest way to do this is to use this URL https://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_URL replacing YOUR_APP_ID and YOUR_URL with your App ID and then a URL that is derived from your endpoint (or even just your endpoint). When you load that URL, you’ll be prompted to add your app to a page – select the page you want and submit the form.

4. The final piece is throwing together the actual PHP script. You’ll need the Facebook PHP SDK available on GitHub – https://github.com/facebook/php-sdk. Clone that and then this is the PHP script you’ll need:

And thats it! Now you’ll be able to gate content from non-fans while growing the fanbase of your Facebook Page.

Drop any questions in the comments.