Skip to content

Commit c825741

Browse files
committed
Skip valid_class check if no class defined
heartcombo#1656 Previously, we would check for validity all the time, even if the outcome of the check added no class. This meant that there was no way to opt out of the check in cases where it was expensive (if the file is stored in S3, in our example). Now, we only check for validity if there is a valid_class defined to be added if the field is valid.
1 parent 4dd9261 commit c825741

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

lib/simple_form/wrappers/root.rb

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,16 @@ def html_classes(input, options)
2828
css += SimpleForm.additional_classes_for(:wrapper) do
2929
input.additional_classes + [input.input_class]
3030
end
31-
css << (options[:wrapper_error_class] || @defaults[:error_class]) if input.has_errors?
32-
css << (options[:wrapper_hint_class] || @defaults[:hint_class]) if input.has_hint?
33-
css << (options[:wrapper_valid_class] || @defaults[:valid_class]) if input.valid?
31+
css << html_class(:error_class, options) { input.has_errors? }
32+
css << html_class(:hint_class, options) { input.has_hint? }
33+
css << html_class(:valid_class, options) { input.valid? }
3434
css.compact
3535
end
36+
37+
def html_class(key, options)
38+
css = (options[:"wrapper_#{key}"] || @defaults[key])
39+
css if css && yield
40+
end
3641
end
3742
end
3843
end

test/form_builder/wrapper_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,15 @@ class WrapperTest < ActionView::TestCase
5959
assert_no_select 'input.is-invalid'
6060
end
6161

62+
test 'wrapper does not determine if valid class is needed when it is set to nil' do
63+
def @user.name; raise BOOM; end
64+
with_form_for @user, :name, as: :file, wrapper: custom_wrapper_with_input_valid_class(valid_class: nil)
65+
assert_select 'div'
66+
assert_select 'input'
67+
assert_no_select 'div.field_with_errors'
68+
assert_no_select 'input.is-invalid'
69+
end
70+
6271
test 'wrapper adds hint class for attribute with a hint' do
6372
with_form_for @user, :name, hint: 'hint'
6473
assert_select 'div.field_with_hint'

test/support/misc_helpers.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -213,8 +213,8 @@ def custom_wrapper_with_input_error_class
213213
end
214214
end
215215

216-
def custom_wrapper_with_input_valid_class
217-
SimpleForm.build tag: :div, class: "custom_wrapper", valid_class: :field_without_errors do |b|
216+
def custom_wrapper_with_input_valid_class(valid_class: :field_without_errors)
217+
SimpleForm.build tag: :div, class: "custom_wrapper", valid_class: valid_class do |b|
218218
b.use :label
219219
b.use :input, class: 'inline-class', valid_class: 'is-valid'
220220
end

0 commit comments

Comments
 (0)