From 303fb1fb1feef1d8e231d49e6f53ad6f10b312a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 17 May 2010 11:08:47 +0200 Subject: [PATCH] Tidy up previous commit. --- CHANGELOG.rdoc | 3 +++ lib/simple_form/inputs/base.rb | 11 ++++++----- test/form_builder_test.rb | 8 +++++++- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index dd7df4ba..3e52844e 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -1,3 +1,6 @@ +* enhancements + * added support to presence validation to check if attribute is required or not (by github.com/gcirne) + == 1.1.3 * deprecation diff --git a/lib/simple_form/inputs/base.rb b/lib/simple_form/inputs/base.rb index ebb42d70..98a990fe 100644 --- a/lib/simple_form/inputs/base.rb +++ b/lib/simple_form/inputs/base.rb @@ -49,12 +49,13 @@ module SimpleForm end def attribute_required? - klass = object.class - if defined? klass.validators_on - return options[:required] unless options[:required].nil? - return klass.validators_on(attribute_name).map {|validator| validator.kind}.include?(:presence) + if options.key?(:required) + options[:required] + elsif defined?(object.class.validators_on) + object.class.validators_on(attribute_name).any? { |v| v.kind == :presence } + else + true end - options[:required] != false end def required_class diff --git a/test/form_builder_test.rb b/test/form_builder_test.rb index db2d4ad5..b41fe3fe 100644 --- a/test/form_builder_test.rb +++ b/test/form_builder_test.rb @@ -229,6 +229,7 @@ class FormBuilderTest < ActionView::TestCase assert_select 'span.error#cool', "can't be blank" end + # REQUIRED AND PRESENCE VALIDATION test 'builder input should obtain required from ActiveModel::Validations when it is included' do with_form_for @validating_user, :name assert_select 'input.required#validating_user_name' @@ -347,9 +348,14 @@ class FormBuilderTest < ActionView::TestCase assert_select 'label.string[for=user_name]', /Name/ end + test 'builder should add a required class to label if the attribute is required' do + with_label_for @validating_user, :name + assert_select 'label.string[for=validating_user_name]', /Name/ + end + test 'builder should allow passing options to label tag' do with_label_for @user, :name, :label => 'My label', :id => 'name_label' - assert_select 'label.string.required#name_label', /My label/ + assert_select 'label.string#name_label', /My label/ end test 'builder should fallback to default label when string is given' do