Sha256: 02188effce6f2beb30384bffa85f4eb1e46d5f531fcaaa5846321e2cb0addfac

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

module BraDocuments
  class Formatter
    NOT_NUMBER = /\D/
    FORMATS = {
      cpf: { pattern: /\A(\d{3})(\d{3})(\d{3})(\d{2})\z/, mask: '%s.%s.%s-%s' },
      cnpj: { pattern: /\A(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})\z/, mask: '%s.%s.%s/%s-%s' }
    }.freeze

    class << self
      # Formats a only numbers CPF or CNPJ in their own mask
      #
      # BraDocuments::Formatter.format('86027265892', as: :cpf) # => "860.272.658-92"
      # BraDocuments::Formatter.format('53855973879456', as: :cnpj) # => "53.855.973/8794-56"
      def format(number, as:)
        raise ArgumentError, "\"#{number.inspect}\" must be a String." unless number.is_a?(String)
        unless known_format?(as)
          raise ArgumentError, "Format \"#{as}\" is not know. Known formats: #{known_formats.join(', ')}."
        end

        format_data = FORMATS[as]

        Kernel.format(format_data[:mask], *format_data[:pattern].match(number).captures)
      end

      # Formats removing all not number caracters from string.
      #
      # BraDocuments::Formatter.raw('860.272.658-9') # => "286027265892"
      # BraDocuments::Formatter.format('53.855.973/8794-56') # => "53855973879456"
      def raw(number)
        raise ArgumentError, "\"#{number.inspect}\" must be a String." unless number.is_a?(String)

        number.gsub(NOT_NUMBER, '')
      end

      private

      def known_formats
        @known_formats ||= FORMATS.keys
      end

      def known_format?(format)
        known_formats.include?(format)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bra_documents-1.0.2 lib/bra_documents/formatter.rb
bra_documents-1.0.1 lib/bra_documents/formatter.rb