From c81f3ca9949eb564a806d87cc03deb310107e4a7 Mon Sep 17 00:00:00 2001 From: Daniel Schierbeck Date: Sun, 5 Sep 2010 23:19:45 +0800 Subject: [PATCH] Set the min attribute when there's a >= validation --- lib/simple_form/inputs/numeric_input.rb | 22 +++++++++++++++++++++- test/inputs_test.rb | 5 +++++ test/support/models.rb | 1 + test/test_helper.rb | 1 + 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/simple_form/inputs/numeric_input.rb b/lib/simple_form/inputs/numeric_input.rb index c711c8ae..038176d1 100644 --- a/lib/simple_form/inputs/numeric_input.rb +++ b/lib/simple_form/inputs/numeric_input.rb @@ -9,12 +9,32 @@ module SimpleForm input_options = super input_options[:type] ||= "number" input_options[:size] ||= SimpleForm.default_input_size + + infer_attrs_from_validations(input_options) + input_options end def input_html_classes super.unshift("numeric") end + + protected + + def infer_attrs_from_validations(input_options) + obj = @builder.object + + return unless obj.class.respond_to?(:validators_on) + + validators = obj.class.validators_on(attribute_name) + num_validator = validators.find {|v| v.is_a?(ActiveModel::Validations::NumericalityValidator) } + + return if num_validator.nil? + + options = num_validator.__send__(:options) + + input_options[:min] ||= options[:greater_than_or_equal_to] + end end end -end \ No newline at end of file +end diff --git a/test/inputs_test.rb b/test/inputs_test.rb index ce663b22..05c76811 100644 --- a/test/inputs_test.rb +++ b/test/inputs_test.rb @@ -54,6 +54,11 @@ class InputTest < ActionView::TestCase assert_select 'input[type=number].integer#user_age' end + test 'input should generate a min attribute when such a validation exists in the model' do + with_input_for @validating_user, :age, :integer + assert_select 'input[min=18]' + end + test 'input should generate a float text field for float attributes ' do with_input_for @user, :age, :float assert_select 'input[type=number].float#user_age' diff --git a/test/support/models.rb b/test/support/models.rb index 1134728f..b2498786 100644 --- a/test/support/models.rb +++ b/test/support/models.rb @@ -118,4 +118,5 @@ class ValidatingUser < User include ActiveModel::Validations validates :name, :presence => true validates :company, :presence => true + validates_numericality_of :age, :greater_than_or_equal_to => 18 end diff --git a/test/test_helper.rb b/test/test_helper.rb index 6f92233f..78e555dd 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -60,6 +60,7 @@ class ActionView::TestCase :name => 'New in Simple Form!', :description => 'Hello!', :created_at => Time.now, + :age => 19, :company => 1 }.merge(options)) end