Mustache support for Rails 3: template handler

I sure am glad I went to the Bmore on Rails hack night yesterday. I got some invaluable help from Paul Barry hacking together a working template handler for mustache in Rails 3.

Magic strings!

Part of the fun was learning how a template handler, subclassing ActionView::Template::Handler, must implement a compile method that takes an ActionView::Template as an argument and returns a string that can be eval’d to do the actual HTML rendering. Paul and I worked with a gist from Martin Gamsjaeger (Thanks, Martin!) and determined that what we needed to get it working in a project at lib/mustache/rails.rb was to move some of Martin’s code into the magic string and alter it a bit so that the view object in the mustache view classes would, as Martin intended, get all the instance variables from the controller and declare attr_readers to access them. Our version of the gist is here.

In the course of pairing with Paul, I learned why a lot of Mustache code I’ve seen opens the Mustache class to define subclasses and modules: since Ruby classes are just special modules, you can open them as you would a module. So I can rename my generator ‘mustache.’ He also showed me how the mustache template helper will expect my view classes to be module-scoped and thus named something like Widgets::Show instead of WidgetShow. That seems much cleaner.

Next steps

I’m still just getting started. Next up:

  • Clean up the template helper code;
  • Fix my existing generator code to play well with the helper;
  • Figure out how to do forms and layouts with mustache;
  • See if our work can benefit the Tilt project;
  • Make a gem to package this all up.

Thanks to the local and global Ruby communities, I anticipate the rest of the project should be as much fun as the beginning.