Class: Volt::NumericalityValidator
- Defined in:
- lib/volt/models/validators/numericality_validator.rb
Instance Attribute Summary collapse
-
#errors ⇒ Object
readonly
Returns the value of attribute errors.
Class Method Summary collapse
Instance Method Summary collapse
- #add_error(error) ⇒ Object
-
#check_errors ⇒ Object
Looks at the value.
-
#initialize(model, field_name, args) ⇒ NumericalityValidator
constructor
A new instance of NumericalityValidator.
Constructor Details
#initialize(model, field_name, args) ⇒ NumericalityValidator
Returns a new instance of NumericalityValidator.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/volt/models/validators/numericality_validator.rb', line 10 def initialize(model, field_name, args) @field_name = field_name @args = args @errors = {} @value = model.get(field_name) # Convert to float if it is a string for a float # The nil check and the nan? check are only require for opal 0.6 unless @value.nil? @value = Kernel.Float(@value) rescue nil @value = nil if RUBY_PLATFORM == 'opal' && @value.nan? end check_errors end |
Instance Attribute Details
#errors ⇒ Object (readonly)
Returns the value of attribute errors.
8 9 10 |
# File 'lib/volt/models/validators/numericality_validator.rb', line 8 def errors @errors end |
Class Method Details
.validate(model, field_name, args) ⇒ Object
3 4 5 6 |
# File 'lib/volt/models/validators/numericality_validator.rb', line 3 def self.validate(model, field_name, args) # Construct the class and return the errors new(model, field_name, args).errors end |
Instance Method Details
#add_error(error) ⇒ Object
27 28 29 30 |
# File 'lib/volt/models/validators/numericality_validator.rb', line 27 def add_error(error) field_errors = (@errors[@field_name] ||= []) field_errors << error end |
#check_errors ⇒ Object
Looks at the value
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/volt/models/validators/numericality_validator.rb', line 33 def check_errors if @value && @value.is_a?(Numeric) if @args.is_a?(Hash) @args.each do |arg, val| case arg when :min if @value < val add_error("number must be greater than #{val}") end when :max if @value > val add_error("number must be less than #{val}") end end end end else = (@args.is_a?(Hash) && @args[:message]) || 'must be a number' add_error() end end |