views:

146

answers:

0

So I'm new to Rails and I'm trying to figure out what the canonical way to add custom form elements is. Currently the way I'm doing it is super grotty.

module ActionView
  module Helpers
    module FormOptionsHelper
      def some_new_field(object, method, options = {}, html_options = {})
          #code code
      end
    end
    class FormBuilder 
      def contract_year_select(method, options = {}, html_options = {})
        @template.some_new_field(@object_name, method, objectify_options(options), @default_options.merge(html_options))
      end
    end
  end
end

I have seen this however.

class Forms::ApplicationFormBuilder < ActionView::Helpers::FormBuilder
  Forms::ApplicationHelper.instance_methods.each do |selector|
    src = <<-end_src
      def #{selector}(method, options = {})
        @template.send(#{selector.inspect}, @object_name, method, objectify_options(options))
      end
    end_src
    class_eval src, __FILE__, __LINE__
  end

  private

  def objectify_options(options)
    @default_options.merge(options.merge(:object => @object))
  end
end

(from here)

Extending FormBuilder seems like a better solution than duck punching it. Is there some other way to do this that doesn't require directly copying parts of the FormBuilder class into my custom one?