Skip to content

Instantly share code, notes, and snippets.

@DBA
Created January 2, 2009 22:11
Show Gist options
  • Save DBA/42712 to your computer and use it in GitHub Desktop.
Save DBA/42712 to your computer and use it in GitHub Desktop.
class GeneralPurposeFormBuilder < ActionView::Helpers::FormBuilder
%w[text_field text_area collection_select].each do |method_name|
define_method(method_name) do |field_name, *args|
@template.content_tag(:div, field_label(field_name, *args) +
"<br />" + super + field_hint(field_name, *args),
:id => field_container_name(field_name),
:class => "form_field")
end
end
def date_select(field_name, *args)
options = args.extract_options!
if options[:use_defaults]
options[:start_year] = Time.now.year - 67
options[:end_year] = Time.now.year - 13
options[:order] = [:day, :month, :year]
options[:include_blank] = true;
options[:default] = { }
end
*args = *(args + [options])
@template.content_tag(:div, field_label(field_name, *args) + "<br />" + super + field_hint(field_name, *args),
:id => field_container_name(field_name), :class => "form_field")
end
def check_box(field_name, *args)
@template.content_tag(:div, super + " " + field_label(field_name, *args) + field_hint(field_name, *args),
:id => field_container_name(field_name), :class => "form_field")
end
def submit(*args)
cancel_link = ""
options = args.extract_options!
if options[:cancel_link_url]
cancel_link << "&nbsp;or&nbsp;"
cancel_link << @template.link_to(options[:cancel_link_text] ? options[:cancel_link_text] : "cancel",
options[:cancel_link_url])
cancel_link = @template.content_tag(:span, cancel_link, :id => field_container_name("cancel"))
end
@template.content_tag(:div, super + cancel_link, :id => field_container_name("submit"), :class => "form_submit")
end
private
def field_container_name(field_name)
"#{object.class.to_s.downcase}_#{field_name}_field"
end
def field_label(field_name, *args)
options = args.extract_options!
options[:label_class] = field_required?(field_name) ? "required_field_label" : "field_label"
label(field_name, options[:label], :class => options[:label_class])
end
def field_hint(field_name, *args)
options = args.extract_options!
if options[:hint]
@template.content_tag(:div, options[:hint], :id => "#{field_name}_hint", :class => "field_help")
else
''
end
end
def field_required?(field_name)
object.class.reflect_on_validations_for(field_name).map(&:macro).include?(:validates_presence_of)
end
def objectify_options(options)
super.except(:label, :label_class, :hint, :cancel_link_url, :cancel_link_text, :use_defaults)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment