forked from heartcombo/simple_form
/
form_helper.rb
56 lines (51 loc) · 1.98 KB
/
form_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module SimpleForm
module ActionViewExtensions
# This modules create simple form wrappers around default form_for,
# fields_for and remote_form_for.
#
# Example:
#
# simple_form_for @user do |f|
# f.input :name, :hint => 'My hint'
# end
#
module FormHelper
# based on what is done in formtastic
# http://github.com/justinfrench/formtastic/blob/master/lib/formtastic.rb#L1706
@@default_field_error_proc = nil
# 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 with_custom_field_error_proc(&block)
@@default_field_error_proc = ::ActionView::Base.field_error_proc
::ActionView::Base.field_error_proc = FIELD_ERROR_PROC
result = yield
::ActionView::Base.field_error_proc = @@default_field_error_proc
result
end
[:form_for, :fields_for, :remote_form_for].each do |helper|
class_eval <<-METHOD, __FILE__, __LINE__
def simple_#{helper}(record_or_name_or_array, *args, &block)
options = args.extract_options!
options[:builder] = SimpleForm::FormBuilder
css_class = case record_or_name_or_array
when String, Symbol then record_or_name_or_array.to_s
when Array then dom_class(record_or_name_or_array.last)
else dom_class(record_or_name_or_array)
end
options[:html] ||= {}
options[:html][:class] = "simple_form \#{css_class} \#{options[:html][:class]}".strip
with_custom_field_error_proc do
#{helper}(record_or_name_or_array, *(args << options), &block)
end
end
METHOD
end
end
end
end
ActionView::Base.send :include, SimpleForm::ActionViewExtensions::FormHelper