2010-02-06 21:21:26 +00:00
|
|
|
module SimpleForm
|
|
|
|
module Inputs
|
|
|
|
class NumericInput < Base
|
|
|
|
def input
|
2010-11-07 09:41:33 +00:00
|
|
|
input_html_options[:type] ||= "number"
|
|
|
|
input_html_options[:size] ||= SimpleForm.default_input_size
|
|
|
|
input_html_options[:step] ||= 1 if integer?
|
|
|
|
infer_attributes_from_validations!
|
2010-02-06 21:21:26 +00:00
|
|
|
@builder.text_field(attribute_name, input_html_options)
|
|
|
|
end
|
|
|
|
|
2010-06-01 21:37:53 +00:00
|
|
|
def input_html_classes
|
|
|
|
super.unshift("numeric")
|
|
|
|
end
|
2010-09-05 15:19:45 +00:00
|
|
|
|
|
|
|
protected
|
|
|
|
|
2010-11-07 09:41:33 +00:00
|
|
|
def has_placeholder?
|
|
|
|
placeholder_present?
|
|
|
|
end
|
|
|
|
|
|
|
|
def infer_attributes_from_validations!
|
2010-09-14 03:40:03 +00:00
|
|
|
return unless has_validators?
|
2010-09-05 15:19:45 +00:00
|
|
|
|
2010-09-14 03:40:03 +00:00
|
|
|
numeric_validator = find_numericality_validator or return
|
|
|
|
validator_options = numeric_validator.options
|
2010-09-05 15:19:45 +00:00
|
|
|
|
2010-11-07 09:41:33 +00:00
|
|
|
input_html_options[:min] ||= minimum_value(validator_options)
|
|
|
|
input_html_options[:max] ||= maximum_value(validator_options)
|
2010-09-05 16:47:54 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def integer?
|
|
|
|
input_type == :integer
|
2010-09-05 15:19:45 +00:00
|
|
|
end
|
2010-09-05 15:54:00 +00:00
|
|
|
|
2010-09-14 03:40:03 +00:00
|
|
|
def minimum_value(validator_options)
|
|
|
|
if integer? && validator_options.key?(:greater_than)
|
|
|
|
validator_options[:greater_than] + 1
|
|
|
|
else
|
|
|
|
validator_options[:greater_than_or_equal_to]
|
|
|
|
end
|
2010-09-05 16:46:02 +00:00
|
|
|
end
|
|
|
|
|
2010-09-14 03:40:03 +00:00
|
|
|
def maximum_value(validator_options)
|
|
|
|
if integer? && validator_options.key?(:less_than)
|
|
|
|
validator_options[:less_than] - 1
|
|
|
|
else
|
|
|
|
validator_options[:less_than_or_equal_to]
|
|
|
|
end
|
2010-09-05 16:46:02 +00:00
|
|
|
end
|
|
|
|
|
2010-09-14 03:40:03 +00:00
|
|
|
def find_numericality_validator
|
|
|
|
attribute_validators.find { |v| ActiveModel::Validations::NumericalityValidator === v }
|
2010-09-05 15:54:00 +00:00
|
|
|
end
|
2010-02-06 21:21:26 +00:00
|
|
|
end
|
|
|
|
end
|
2010-09-05 15:19:45 +00:00
|
|
|
end
|