0

I create a custom FormBuilder for my application, but I dont understand why I need to pass tow parameters as follow:

f.text_field :my_model, :my_field

Here is my builder:

class AceBuilder < ActionView::Helpers::FormBuilder
  %w[text_field password_field text_area].each do |method_name|
    define_method(method_name) do |object_name, method, *args|
      options = args.extract_options!

      @template.content_tag(:div, :class => "control-group #{@object.errors[method].length > 0 ? 'error' : ''}") do
        @template.concat(
            @template.content_tag(:label,
                                  options[:label] || method.to_s.humanize,
                                  :class => 'control-label',
                                  :for => "#{object_name}_#{method}"))
        @template.concat(
            @template.content_tag(:div,
                                  :class => "controls") do
              @template.concat(super(method))

              @template.concat(
                  @template.content_tag(:span,
                                        @object.errors[method].join,
                                        :for => "#{object_name}_#{method}",
                                        :class => "help-inline"
                  )
              )
            end
        )
      end
    end
  end

I know that

define_method(method_name) do |object_name, method, *args|

has two parameters, so my question is:

How can I write this FormBuilder, such a way that I can call it like this:

f.text_field :my_field

Thanks.

Beetlejuice
  • 4,292
  • 10
  • 58
  • 84

1 Answers1

0

That was easy, after I realize how: replace object_name by @object_name

class AceBuilder < ActionView::Helpers::FormBuilder
  %w[text_field password_field text_area].each do |method_name|
    define_method(method_name) do |method, *args|
      options = args.extract_options!

      @template.content_tag(:div, :class => "control-group #{@object.errors[method].length > 0 ? 'error' : ''}") do
        @template.concat(
            @template.content_tag(:label,
                                  options[:label] || method.to_s.humanize,
                                  :class => 'control-label',
                                  :for => "#{@object_name}_#{method}"))
        @template.concat(
            @template.content_tag(:div,
                                  :class => "controls") do
              @template.concat(super(method))

              @template.concat(
                  @template.content_tag(:span,
                                        @object.errors[method].join,
                                        :for => "#{@object_name}_#{method}",
                                        :class => "help-inline"
                  )
              )
            end
        )
      end
    end
  end
Beetlejuice
  • 4,292
  • 10
  • 58
  • 84