Sha256: 67071eddb0c67d2f94b7e7079f8448d375d6288013f378fbda381af7464a7dc2

Contents?: true

Size: 1.01 KB

Versions: 1

Compression:

Stored size: 1.01 KB

Contents

# frozen_string_literal: true

module BraDocumentValidation
  class CPFOrCNPJValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      return record.errors.add(attribute, error_message(:invalid_format)) unless valid_format?(value)

      record.errors.add(attribute, error_message(:invalid_verification_digit)) unless valid_verification_digit?(value)
    end

    private

    def valid_format?(document)
      BraDocuments::Matcher.match?(document.to_s, kind: :cpf, mode: document_format) ||
        BraDocuments::Matcher.match?(document.to_s, kind: :cnpj, mode: document_format)
    end

    def valid_verification_digit?(document)
      BraDocuments::CPFGenerator.valid_verification_digit?(document: document.to_s) ||
        BraDocuments::CNPJGenerator.valid_verification_digit?(document: document.to_s)
    end

    def document_format
      options[:formatted] ? :formatted : :raw
    end

    def error_message(default_message)
      options.fetch(:message, default_message)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bra_document_validation-1.0.2 lib/bra_document_validation/cpf_or_cnpj_validator.rb