Module: AmountField::ActiveRecord::Validations::ClassMethods

Defined in:
lib/amount_field/validations.rb

Instance Method Summary collapse

Instance Method Details

#validates_amount_format_of(*attr_names) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/amount_field/validations.rb', line 17

def validates_amount_format_of(*attr_names)
  # code before validates_each is called only once!
  configuration = attr_names.extract_options!

  define_special_setter(attr_names)

  # the following code defines the callbacks methods that are called on every validation
  validates_each(attr_names, configuration) do |record, attr_name, value|
    # in case there is no assignment via 'amount_field_XXX=' method, we don't need to validate.
    next unless record.instance_variable_defined?("@#{special_method_name(attr_name)}")

    # get the original assigned value first to always run the validation for this value!
    # if we us 'before_type_cast' here, we would get the converted value and not the 
    # original value if we call the validation twice.
    original_value = record.instance_variable_get("@#{special_method_name(attr_name)}")
    original_value ||= record.send("#{attr_name}_before_type_cast") || value

    # in case nil or blank is allowed, we don't validate
    next if configuration[:allow_nil] and original_value.nil?
    next if configuration[:allow_blank] and original_value.blank?

    converted_value = convert(original_value, format_configuration(configuration))

    if valid_format?(original_value, format_configuration(configuration))
      # assign converted value to attribute so other validations macro can work on it 
      # and the getter returns a value
      record.send("#{attr_name}=", converted_value)
    else  
      # assign original value as AssignedValue so multiple calls of this validation will
      # consider the value still as invalid.
      record.send("#{attr_name}=", original_value)
      record.errors.add(attr_name, 
        build_error_message(configuration[:message], {
          :value => original_value, 
          :format_example => valid_format_example(format_configuration(configuration))
        })
      )
    end  

  end
end