Recently I’ve been working on Tubby, a library for writing HTML templates in plain Ruby:

tmpl = Tubby . new { | t | t . doctype! t . h1 ( "Hello #{ current_user } !" ) t << Avatar . new ( current_user ) t . ul { t . li ( "Tinky Winky" ) t . li ( "Dipsy" , class: "active" ) t . li ( "Laa-Laa" ) t . li ( "Po" ) } } puts tmpl . to_s

This is hardly a new idea: Markaby was released back in 2009, and since then we’ve also seen Tagz, Erector, and Mab. Tubby might seem like nothing more than a more syntactically verbose, less feature-rich alternative, but there is in fact a very concrete philosophy which has lead to this design. The goal of Tubby is to provide a way to write composable templates where it gets out of your way so you can use Ruby’s built-in features (classes and modules) yourself. This has lead to the following decisions:

You don’t need to inherit from a class or include a module to use Tubby.

Tubby doesn’t use instance_eval so you never need to worry about what self is.

so you never need to worry about what is. Clear separation between your object and the renderer (the t -object above).

-object above). Any object can behave as a template by implementing #to_tubby .

. Tiny API with very few features: Easy to learn and easy to read, at the cost of sometimes being more verbose.

If you haven’t already, I recommend reading through the "Basic usage"-section of the README to get a feel of the features of Tubby. The real power of Tubby comes in how you can use it with plain Ruby classes to build maintainable, composable templates. In this article I will describe various patterns I’ve discovered.