Class: Volt::NumericalityValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/volt/models/validators/numericality_validator.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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
26
27
28
29
# 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?
    begin
      @value = Kernel.Float(@value)
    rescue ArgumentError => e
      @value = nil
    end
    # @value = nil if RUBY_PLATFORM == 'opal' && @value.nan?
  end

  check_errors
end

Instance Attribute Details

#errorsObject (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



31
32
33
34
# File 'lib/volt/models/validators/numericality_validator.rb', line 31

def add_error(error)
  field_errors = (@errors[@field_name] ||= [])
  field_errors << error
end

#check_errorsObject

Looks at the value



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 37

def check_errors
  if @value && @value.is_a?(Numeric)
    if @args.is_a?(Hash)

      @args.each do |arg, val|
        case arg
        when :min
          add_error("number must be greater than #{val}") if @value < val
        when :max
          add_error("number must be less than #{val}") if @value > val
        end
      end

    end
  else
    message = (@args.is_a?(Hash) && @args[:message]) || 'must be a number'
    add_error(message)
  end
end