Skip to content

Instantly share code, notes, and snippets.

@sr75
Created May 29, 2013 06:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sr75/5668402 to your computer and use it in GitHub Desktop.
Save sr75/5668402 to your computer and use it in GitHub Desktop.
How to override default rails ActionView::Base.field_error_proc for individual form builders
module SubmissionFormHelper
# Override the default ActiveRecordHelper behaviour of wrapping the input.
# This gets taken care of semantically by adding an error class to the wrapper tag
# containing the input.
#
FIELD_ERROR_PROC = proc do |html_tag, instance_tag|
html_tag
end
def submission_form_for(record, options = {}, &block)
options[:builder] = SubmissionFormBuilder
with_submission_form_field_error_proc do
form_for(record, options, &block)
end
end
def submission_fields_for(record_name, record_object = nil, options = {}, &block)
options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
options[:builder] ||= SubmissionFormBuilder
with_submission_form_field_error_proc do
fields_for(record_name, record_object, options, &block)
end
end
private
def with_submission_form_field_error_proc
default_field_error_proc = ::ActionView::Base.field_error_proc
begin
::ActionView::Base.field_error_proc = FIELD_ERROR_PROC
yield
ensure
::ActionView::Base.field_error_proc = default_field_error_proc
end
end
class SubmissionFormBuilder < ActionView::Helpers::FormBuilder
end
end
@scarfacedeb
Copy link

Thank you for this snippet.
It seems like there's really no other way to set builder-specific field_error_proc.

What about performance?
Is it a code smell?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment