Skip to content

Instantly share code, notes, and snippets.

@kakra
Created August 12, 2009 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakra/166448 to your computer and use it in GitHub Desktop.
Save kakra/166448 to your computer and use it in GitHub Desktop.
Auto-labelling formbuilder, use with :builder => LabellingFormBuilder
module ApplicationHelper
def labelled_form_for(name, object, options, &proc)
form_for(name, object, options.merge(:builder => LabellingFormBuilder), &proc)
end
def multipart_form_for(name, object, options, &proc)
html_options = options.delete(:html) || {}
html_options.merge!(:multipart => true)
form_for(name, object, options.merge(:html => html_options), &proc)
end
def labelled_multipart_form_for(name, object, options, &proc)
multipart_form_for(name, object, options.merge(:builder => LabellingFormBuilder), &proc)
end
end
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
[:text_field, :password_field, :time_select, :date_select, :datetime_select, :file_field, :text_area].each do |selector|
src = <<-SRC
def #{selector.to_s}(method, options = {})
html = super(method, options)
label = options.delete(:label) if options.is_a? Hash
label ||= method.to_s.humanize
<<-HTML
<label for="#\{object_name}_#\{method.to_s}">#\{label.to_s}</label><br/>
#\{html}
HTML
end
SRC
class_eval src, __FILE__, __LINE__
end
[:check_box].each do |selector|
src = <<-SRC
def #{selector.to_s}(method, options = {}, checked_value = "1", unchecked_value = "0")
html = super(method, options, checked_value, unchecked_value)
label = options.delete(:label) if options.is_a? Hash
label ||= method.to_s.humanize + "?"
<<-HTML
<label for="#\{object_name}_#\{method.to_s}">#\{label.to_s}</label><br/>
#\{html}
HTML
end
SRC
class_eval src, __FILE__, __LINE__
end
[:select, :country_select].each do |selector|
src = <<-SRC
def #{selector.to_s}(method, choices, options = {}, html_options = {})
html = super(method, choices, options, html_options)
label = options.delete(:label) if options.is_a? Hash
label ||= method.to_s.humanize
<<-HTML
<label for="#\{object_name}_#\{method.to_s}">#\{label.to_s}</label><br/>
#\{html}
HTML
end
SRC
class_eval src, __FILE__, __LINE__
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment