rails recipes -- Creating a Custom Form Builder

Now that you have that working, you can’t help but ask yourself what
other elements you constantly find yourself putting into forms. How
about alternate the color of each row in a form? Here’s a form builder
that does that:
Download CustomFormBuilder/app/helpers/application_helper.rb
   class TabularAlternatingColorFormBuilder < ActionView::Helpers::FormBuilder
      (field_helpers - %w(check_box radio_button hidden_field)).each do |selector|
        src = <<-END_SRC
           def #{selector}(field, options = {})
             @template.content_tag("tr" ,
                @template.content_tag("td" , field.to_s.humanize + ":" ) +
                @template.content_tag("td" , super),
                   :class => (@alt = (@alt ? false : true)) ? "alt-row" : "" )
           end
        END_SRC
        class_eval src, __FILE__, __LINE__
      end
end
def tabular_form_with_alternating_colors_for(name,
                                                              object = nil,
                                                              options = nil,
                                                              &proc)
      concat("<table>" , proc.binding)
      form_for(name,
                 object,
                 (options||{}).merge(:builder => TabularAlternatingColorFormBuilder),
                 &proc)
      concat("</table>" , proc.binding)
end

This builder uses the instance variable @alt to toggle the CSS class
name with each table row. Adding a CSS snippet like the following to
your application’s style sheet will give you a nice, readable alternating
table row effect:
.alt-row {
   background: #fab444;
}

你可能感兴趣的:(css,Ruby,Rails)