Skip to content

Instantly share code, notes, and snippets.

@sbellware
Created January 25, 2011 17:51
Show Gist options
  • Save sbellware/795297 to your computer and use it in GitHub Desktop.
Save sbellware/795297 to your computer and use it in GitHub Desktop.
An Alternative to All-or-Nothing Custom Form Builder Replacement

An Alternative to All-or-Nothing Custom Form Builder Replacement

Background

Replacing Rails' default form builder with a custom form builder is a typical way of adding custom form helpers to a Rails application.

The typical way of doing this is:

ActionView::Base.default_form_builder = MyCustomFormBuilder

The custom form builder is usually a subclass of the default form builder:

class MyCustomFormBuilder < ActionView::Helpers::FormBuilder
  # form helpers here
end

NOTE: For a good example of creating a custom form builder, see:
http://st-on-it.blogspot.com/2009/07/fixing-rails-forms-builder.html

Problem

Here are a couple of situations where the default approach breaks down in practice:

  • You're using a Rails form plugin that replaces the default form builder, and you have your own custom form builder
  • You're using a combination of Rails form plugins where each expects to be able to install by replacing the existing form builder. In this case one of the form builders will replace the other.

Solution

Rather than replace the default form builder with a custom form builder, try to write form helpers so that the can be included into the default form builder without having to entirely replace the form builder that is already in-place.

Encapsulate your custom form helpers in a module, and add the module to the default form helper during initialization (eg: from a Rails initializer):

ActionView::Base.default_form_builder.class_eval do
  include MyCustomFormHelpers
end

Note

Some form plugins provide extensibility mechanisms that allow you to configure a custom form builder class. Formtastic is a good example:

Formtastic::SemanticFormHelper.builder = MyCustomFormBuilder

This is certainly helpful, but it might not be entirely necessary if form builders are customized by extension rather than replacement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment