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



10
11
12
13
14
15
16
17
18
19
20
21
# 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.read_attribute(field_name)

  # Convert to float if it is a string for a float
  @value = Kernel.Float(@value) rescue nil

  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, old_model, field_name, args) ⇒ Object



3
4
5
6
# File 'lib/volt/models/validators/numericality_validator.rb', line 3

def self.validate(model, old_model, field_name, args)
  # Construct the class and return the errors
  self.new(model, field_name, args).errors
end

Instance Method Details

#add_error(error) ⇒ Object



23
24
25
26
# File 'lib/volt/models/validators/numericality_validator.rb', line 23

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

#check_errorsObject

Looks at the value



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/volt/models/validators/numericality_validator.rb', line 29

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
    message = (@args.is_a?(Hash) && @args[:message]) || 'must be a number'
    add_error(message)
  end
end