Sha256: b2e994961caf996a31da58b63979001a14acf7e8a0352acd2c98645ebf190d84

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

require 'correios-cep'
require 'active_model'

module ActiveModel
  module Validations
    class CorreiosCepValidator < EachValidator
      CORREIOS_CEP_I18N_SCOPE = 'correios_cep.errors.messages'

      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
                                "#{CORREIOS_CEP_I18N_SCOPE}.connection_failed"
                              rescue ArgumentError
                                "#{CORREIOS_CEP_I18N_SCOPE}.invalid"
                              rescue Net::OpenTimeout
                                "#{CORREIOS_CEP_I18N_SCOPE}.timeouted"
                              end

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

    module HelperMethods
      def validates_correios_cep_of(*attributes)
        validates_with CorreiosCepValidator, _merge_attributes(attributes)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
validates-correios-cep-0.1.0 lib/validates-correios-cep/activemodel.rb