Jamie's Space

JP

Rails 3 Form Builder for Twitter Bootstrap Form Elements

Edit: I have updated this for Bootstrap 2. See the links at the bottom of the page for both versions.

I have been working on a website in my spare time to help me organise my life a bit better, and one of the things that always trips me up with these kinds of projects is the visual style. For a while I had a basic fixed width style I used, but it didn’t really fit properly with what I wanted to build. A little while after I had started, Twitter released Bootstrap, a nice looking CSS framework. I decided to have a go at using it on my site (in a separate git branch of course) and it ended up only taking me less than an hour to get it all up and looks alright.

One thing that bothered me though was the repetition in my forms - the format for showing labels that line up nicely next to the form elements was the same across all input types, and so was the error handling. This got me thinking: why should I retype all of this when the Rails FormBuilder class is already doing half the work? Surely I could just override some of the methods to make this work?

I needed to learn more about Ruby metaprogramming to get it to work - I still wanted the core functionality of the default rails FormBuilder, just with some extra DOM nodes wrapped around it. Ruby lets you redefine methods at runtime, but also allows you to alias the old methods so you can refer to them inside your new version of the method. So I ended up writing a method that does the Bootstrap boilerplate DOM wrapper creation and calls the original method to generate the input element itself.

I still haven’t overridden all of the FormBuilder methods because I need to actually test them (and I don’t have a use for them yet), but the basics are here in this Gist: https://gist.github.com/1236567. The methods I have overridden are in basic_helpers, the ones that output multiple inputs are in multipart_helpers. The great thing is I have only had to add method names to those two arrays as needed - none of the input types have needed special casing. This might not be the case for all of them, but one can only hope. If you do find this useful, or want to add and test some more of the helpers, please fork my Gist and leave me a comment.

Edit: Here are links to both the v1 and v2 form builders:

Version 1 form builder: https://gist.github.com/1236567 Version 2 form builder: https://gist.github.com/1829710