Generic-user-small James West 73 posts

The following excerpt from the book dos not make sense to me

We could then call this method twice in our class definition, once to create a
text_field helper and again to create a text_area helper.

create_tagged_field(:text_field)
create_tagged_field(:text_area)

But even this contains duplication. We could use a loop instead.

[ :text_field, :text_area ].each do |name|
  create_tagged_field(name)
end

We can do even better. The base FormBuilder class defines a collection called
field_helpers—a list of the names of all the helpers it defines. Using this our
final helper class looks like this.

class TaggedBuilder < ActionView::Helpers::FormBuilder

  #  <p>
  Description</label><br/>
  #  <%= form.text_area 'description'  %>
  #</p>

  def self.create_tagged_field(method_name)
    define_method(method_name) do |label, *args|
      @template.content_tag("p",
        @template.content_tag("label" , 
                              label.to_s.humanize, 
                              :for => "#{@object_name}_#{label}") + 
        "<br/>" +
        super)
    end
  end

  field_helpers.each do |name|
    create_tagged_field(name)
  end

end

I think I have completely missed the point about how the specific fields get created.

Given that the view code looks like this

<% form_for :product, :url => { :action => :save }, :builder => TaggedBuilder do |form| %>
  <%= form.text_field 'title'  %>
  <%= form.text_area  'description'  %>
  <%= form.text_field 'image_url'  %>
  <%= submit_tag %>
<% end %>

This code looks to me as if when I call for example
<%= form.text_field 'title'  %>
there will actually be multiple fields generated, one for each type of field_helper in fact as there seems to be no condition in the loop to make sure that the correct type is generated.

Whether I have this wrong or not I think a further explanation in the book would be a really good idea.

Thanks
James

1 post, 1 voice