3.3. Refactoring Forms Using A FormBuilder
Take another look at the code in that form view in the previous section. One thing you should notice is that the pattern of having a table row where the first cell is a caption and the second cell is a form element is repeated over and over. Not only does that make for a lot of unnecessary and error-prone repetition, but all the extra elements make for a lot of clutter and hard-to-read code.
I have to say, I'm familiar with a number of web frameworks that depend on some kind of code or HTML template, and the problem with nearly all of them is that complex code in the view or template becomes difficult to lay out, read, and maintain. Part of this is due to the fact that the code and the HTML have two distinct, intertwined structures, each with its own indentation and layout needs, and these two structures work together only barely. Other frameworks depend on building all the HTML tags programmatically, which can also be difficult to manage in complex cases.
One of the strengths of Ruby on Rails, especially when compared to systems which came before, is an awareness of this problem of structuring views. Rails provides a number of ways to move complex, repetitive code to places where it can be easily consolidated and managed. Throughout the book, you'll take a look at some of these features as they become useful to the project. Right now, it's time to look at custom form builders.
The Rails FormBuilder class is passed to a form_for block ...
Get Professional Ruby on Rails™ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.