Skip to content

Commit

Permalink
allows custom field_error_proc
Browse files Browse the repository at this point in the history
  • Loading branch information
tokland committed Nov 8, 2012
1 parent 521d894 commit 514f158
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
16 changes: 7 additions & 9 deletions lib/formtastic/helpers/form_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ module FormHelper
@@default_form_class = 'formtastic'
mattr_accessor :default_form_class

# Allows to set a custom field_error_proc wrapper. By default this wrapper
# is disabled since `formtastic` already adds an error class to the LI tag
# containing the input. Change this from `config/initializers/formtastic.rb`.
@@field_error_proc = proc { |html_tag, instance_tag| html_tag }
mattr_accessor :field_error_proc

# Wrapper around Rails' own `form_for` helper to set the `:builder` option to
# `Formtastic::FormBuilder` and to set some class names on the `<form>` tag such as
# `formtastic` and the downcased and underscored model name (eg `post`).
Expand Down Expand Up @@ -178,17 +184,9 @@ def semantic_fields_for(record_name, record_object = nil, options = {}, &block)

protected

# Override the default ActiveRecordHelper behaviour of wrapping the input.
# This gets taken care of semantically by adding an error class to the LI tag
# containing the input.
# @private
FIELD_ERROR_PROC = proc do |html_tag, instance_tag|
html_tag
end

def with_custom_field_error_proc(&block)
default_field_error_proc = ::ActionView::Base.field_error_proc
::ActionView::Base.field_error_proc = FIELD_ERROR_PROC
::ActionView::Base.field_error_proc = @@field_error_proc
yield
ensure
::ActionView::Base.field_error_proc = default_field_error_proc
Expand Down
23 changes: 23 additions & 0 deletions spec/helpers/form_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,29 @@
end
end

describe ActionView::Base.field_error_proc do
it 'is set to no-op wrapper by default' do
semantic_form_for(@new_post, :url => '/hello') do |builder|
::ActionView::Base.field_error_proc.call("html").should == "html"
end
end

it 'is set to the configured custom field_error_proc' do
field_error_proc = mock()
Formtastic::Helpers::FormHelper.field_error_proc = field_error_proc
semantic_form_for(@new_post, :url => '/hello') do |builder|
::ActionView::Base.field_error_proc.should == field_error_proc
end
end

it 'is restored to its original value after the form is rendered' do
lambda do
Formtastic::Helpers::FormHelper.field_error_proc = proc {}
semantic_form_for(@new_post, :url => '/hello') { |builder| }
end.should_not change(::ActionView::Base, :field_error_proc)
end
end

describe "with :builder option" do
it "yields an instance of the given builder" do
class MyAwesomeCustomBuilder < Formtastic::FormBuilder
Expand Down

0 comments on commit 514f158

Please sign in to comment.