Sha256: 275abae46f89cfca3172c2d89644afe45fcd67b4962bd9e65bfe2dd851f5d8af

Contents?: true

Size: 955 Bytes

Versions: 5

Compression:

Stored size: 955 Bytes

Contents

require_relative '../commons/mod11'

module BrDocuments
  module CnpjCpf
    module Document
      include Commons::Mod11

      def initialize(number)
        @number = number
      end

      def valid?
        valid_format? && !sequence_of_equal_numbers? && valid_check_digit?
      end

      def formatted
        valid? ? format_number : ''
      end

      private

      def valid_format?
        format_regex.match(@number).present?
      end

      def sequence_of_equal_numbers?
        number_without_mask.chars.uniq.length == 1
      end

      def valid_check_digit?
        weight1, weight2 = weights_for_digital_check

        digital_check1 = generate_check_digit(number_without_mask, weight1)
        digital_check2 = generate_check_digit(number_without_mask, weight2)
        @number[-2, 2] == "#{digital_check1}#{digital_check2}"
      end

      def number_without_mask
        @number.gsub(/[\.\/-]/, '')
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
br_documents-0.2.5 lib/br_documents/cnpj_cpf/document.rb
br_documents-0.2.4 lib/br_documents/cnpj_cpf/document.rb
br_documents-0.2.3 lib/br_documents/cnpj_cpf/document.rb
br_documents-0.2.2 lib/br_documents/cnpj_cpf/document.rb
br_documents-0.2.1 lib/br_documents/cnpj_cpf/document.rb