Sha256: bdebb2b380a36a59d6ba9ee4c58d4a231fa8df60482a7c41b19d7098186b95eb

Contents?: true

Size: 959 Bytes

Versions: 1

Compression:

Stored size: 959 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.split('').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

1 entries across 1 versions & 1 rubygems

Version Path
br_documents-0.2.0 lib/br_documents/cnpj_cpf/document.rb