Rails tip #1: Reloadable custom FormBuilder

August Lilleaas has a nice writeup on making your own FormBuilder. Towards the end, he describes wiring it up as the default:

Create a new file called config/initializers/setup.rb. Or, if you’re on pre-2.0, add it to the bottom of config/environment.rb:

ActionView::Base.default_form_builder = LabellingFormBuilder

Though “proper,” this approach requires restarting the server to see changes in LabellingFormBuilder.

You can avoid restarting the server by doing this instead:

class ActionView::Base
  def self.default_form_builder

It’s a subtle difference, but it provides a nice window into understanding the Dependencies mechanism:

In August’s version, const_missing loads the LabellingFormBuilder class only once, when the initializer is run.

In our version, we’ve tricked const_missing into running on each request by not holding onto the class it loads. That is, instead of caching the class lookup in @@default_form_builder, we’re allowing the lookup to be performed on demand.


5 Rails tips

Each day this week, Joachim and I will post something we’ve learned in our time programming together. It’s fun to do, and we might just win something as well.