Skip to content

Instantly share code, notes, and snippets.

@sofadesign
Created July 13, 2010 09:50
Show Gist options
  • Save sofadesign/473684 to your computer and use it in GitHub Desktop.
Save sofadesign/473684 to your computer and use it in GitHub Desktop.
#
# smart_label_form_builder.rb
#
# original code from:
# http://openmonkey.com/articles/2010/03/rails-labels-with-blocks
#
# --
# adding HAML compatibility (fabrice AT sofa-design DOT net)
#
class SmartLabelFormBuilder < ActionView::Helpers::FormBuilder
include Haml::Helpers if defined? Haml # for compatibility
def label(method, content_or_options_with_block = nil, options = {}, &block)
if !block_given?
# No block, use the standard label helper.
super(method, content_or_options_with_block, options)
else
# We've got a block. This is where we want to do our business.
options = content_or_options_with_block.is_a?(Hash) ? content_or_options_with_block.stringify_keys : {}
if errors_on?(method)
(options['class'] = options['class'].to_s + ' error').strip!
end
if block_is_haml?(block)
init_haml_helpers
capture_haml(options, block) do |options, block|
haml_tag(:label, options) do
haml_concat method.to_s.humanize
haml_concat capture_haml(&block)
end
end
else
@template.content_tag(:label, options, &block)
end
end
end
private
def errors_on?(method)
@object.respond_to?(:errors) && @object.errors.respond_to?(:on) && @object.errors.on(method.to_sym)
end
end
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if instance.error_message.kind_of?(Array)
%(#{html_tag}<div class="error_description">
#{instance.error_message * ', '}</div>)
else
%(#{html_tag}<div class="error_description">
#{instance.error_message}</div>)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment