Teacup handlers, the amazing little tool you might not know you weren't using
a thought by colinta

I finally got a chance to check out Thomas Kadauke’sTinyMon app that he has
graciously posted on github. For one, it’s certainly a well designed, well
written app! The tests in particular are commendable! They put my apps to
shame…

I don’t think I’ve seen someone use this feature of teacup before! It is a
perfect use of a Teacup handler (and I’m encouraging Thomas to add
this to sweettea!)

So, I thought I would explain a little bit about what Teacup handlers are, how
you write them, and I’ll write a bit more about sweettea, and why it is REALLY
what you should be using in conjunction with teacup (even if you don’t use any
other sugarcube features).

What teacup does do

Teacup does, basically, two things:

Provides a DSL to create a view hierarchy (usually from within your
controller). This is designed to be terse, so that your controller isn’t
cluttered with lots of UIView-creation code, and you can assign views to
instance variables with ease.

Provides a DSL to style those views using a CSS-like language, which
usually takes place in Teacup::Stylesheet objects (but doesn’t have to,
you know!). There are a few “magical” keys, but for the most part they
are UIKit methods. Also, the Stylesheet class defines a few helper
methods

extends: is one “magical” key, constraints: is another. I’m not gonna go
into constraints here - check out my post about them.

What teacup can do

Teacup doesn’t just map the style key to a method name. It maintains a list of
“handlers”, and if you know about these and understand them, you can write
stylesheets that are much more expressive!

There aren’t very many built-in handlers; this keeps the teacup library
lean-and-mean. The ones that are there are related to positioning, and some
very basic UIButton handlers, which are offered as examples of what a handler
can do (the original teacup implementation, written by Conrad Irwin
had these helpers as special cases - much later, they were re-implemented as
handlers). Here are all the built in handlers:

Enter SugarCube, stage right

SugarCube offers a TON of shorthands, many of them are related to styling (this
is not an accident, obviously). But you still have to pass the right type to
these methods, so it’s shorter but still not a DSL:

ruby
style :label,
textAlignment: :center.uitextalignment, # this is only a modest "improvement"
textColor: :blue.uicolor # (and many would argue that point!)

Nice, but it doesn’t really look like a stylesheet yet. It’s still a verbose
iOS-y jumble…

(btw, this is going to get added to sweettea SOON, in one form or another)

The sweettea handlers take Teacup out of just a DSL/wrapper for UIKit, into
a full-blown framework to help you style your UIViews. I’ve heard a lot of
comparisons between teacup and Pixate recently, but if you’re not
using teacup handlers, you’re only touching the surface of what teacup can do to
help you!