Class: ValidationProfiler::Rules::DecimalValidationRule

Inherits:
ValidationRule
  • Object
show all
Defined in:
lib/validation_profiler/rules/decimal_validation_rule.rb

Instance Method Summary collapse

Methods inherited from ValidationRule

#get_field_value, #is_required?

Instance Method Details

#error_message(field, attributes = {}, parent = nil) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/validation_profiler/rules/decimal_validation_rule.rb', line 6

def error_message(field, attributes = {}, parent = nil)

  field_name = field.to_s
  if parent != nil
    field_name = "#{parent.to_s}.#{field.to_s}"
  end

  #check if a custom error message has been specified in the attributes
  if attributes[:message] == nil
    #no custom error message has been specified so create the default message.
    "#{field_name} is not a valid Decimal"
  else
    attributes[:message]
  end
end

#is_valid_decimal?(value) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
43
44
45
46
# File 'lib/validation_profiler/rules/decimal_validation_rule.rb', line 40

def is_valid_decimal?(value)
  if value.instance_of? BigDecimal
    true
  else
    (value.to_s =~ /\A[-+]?\d*\.?\d+\z/) == 0
  end
end

#validate(obj, field, attributes = {}, parent = nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/validation_profiler/rules/decimal_validation_rule.rb', line 23

def validate(obj, field, attributes = {}, parent = nil)

  #attempt to get the field value from the object
  field_value = get_field_value(obj, field)

  if !is_required?(field_value, attributes)
    return true
  end

  if !is_valid_decimal?(field_value)
    return false
  end

  return true

end