Class: CuitValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/cuit_validator.rb

Constant Summary collapse

@@default_options =
{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_optionsObject



4
5
6
# File 'lib/cuit_validator.rb', line 4

def self.default_options
  @@default_options
end

.valid?(value, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/cuit_validator.rb', line 8

def self.valid?(value, options = {})
  unless value.empty?
    value.gsub!('-','')
    unless value.length != 11
      xy, dni, z = value[0, 2], value[2, 8], value[10, 1]
      acum = 0
      secuence = [5,4,3,2,7,6,5,4,3,2]
          
      "#{xy}#{dni}".split('').each_with_index { |num, i| acum += num.to_i * secuence[i] }

      z_calculated = (11 - (acum % 11) )

      (z_calculated.to_i == z.to_i)
    end
  else
    true  if options[:allow_empty]
  end
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



27
28
29
30
31
32
# File 'lib/cuit_validator.rb', line 27

def validate_each(record, attribute, value)
  options = @@default_options.merge(self.options)
  unless self.class.valid?(value, options)
    record.errors.add(attribute, options[:message] || :invalid)
  end
end