Class: CnpjValidator

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

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/validates_cnpj/cnpj_validator.rb', line 4

def validate_each(record, attribute, value)
  cnpj = ValidatesCnpj::Cnpj.new(value)

  if cnpj.valid?
    if options[:mask]
      record.send("#{attribute}=", cnpj.number)
    elsif value.is_a?(String) && value != value.upcase
      record.send("#{attribute}=", value.upcase)
    end
  else
    ruby_prior_version_three =
      Gem::Version.new(RUBY_VERSION) < Gem::Version.new('3.0.0')

    if ruby_prior_version_three
      record.errors.add(attribute, :invalid, options)
    else
      record.errors.add(attribute, :invalid, **options)
    end
  end
end