Class: ActiveModel::Validations::CorreiosCepValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/validates-correios-cep/activemodel.rb

Constant Summary collapse

CORREIOS_CEP_I18N_SCOPE =
'correios_cep.errors.messages'

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/validates-correios-cep/activemodel.rb', line 10

def validate_each(record, attribute, value)
  error_message_scope = begin
                          "#{CORREIOS_CEP_I18N_SCOPE}.not_exists" if ::Correios::CEP::AddressFinder.get(value).blank?
                        rescue EOFError, ::HTTP::ConnectionError
                          "#{CORREIOS_CEP_I18N_SCOPE}.connection_failed"
                        rescue ArgumentError
                          "#{CORREIOS_CEP_I18N_SCOPE}.invalid"
                        rescue ::Net::OpenTimeout, ::HTTP::TimeoutError
                          "#{CORREIOS_CEP_I18N_SCOPE}.timeouted"
                        end

  record.errors.add(attribute, I18n.t(error_message_scope, zipcode: value)) if error_message_scope.present?
end