Wednesday, November 14, 2007

Functional Programming In Rails Templates

The use case: you've got a Widget which has_many Things. You want a partial which allows you to include form fragments for several Things the user might want to attach to the Widget. You may or may not already have existing Things. If you do, you want to display them; either way, you want to display three blank form fragments, because even a user who's already got Things attached to their Widget might want to add on a few more. You also need unique div ids on the fragments, so that you can add simple JavaScript to display any necessary new form fragments instantly - without an Ajax round-trip to the server and back.

Vividly picturing the PHP or Java to fulfill that use case could result in an image so frightening it disturbs your sleep for weeks. The Rails way is gorgeous: