Module: CnpjTools

Defined in:
lib/cnpj_tools.rb,
lib/cnpj_tools/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.format(cnpj, format: :masked) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/cnpj_tools.rb', line 25

def format(cnpj, format: :masked)
  tax_id = cnpj_to_s(cnpj)
  return '' unless tax_id.length == 14

  if format == :digits_only
    tax_id
  else
    "#{tax_id[0..1]}.#{tax_id[2..4]}.#{tax_id[5..7]}/#{tax_id[8..11]}-#{tax_id[12..13]}"
  end
end

.return_valid(cnpj, format: :masked) ⇒ Object



36
37
38
# File 'lib/cnpj_tools.rb', line 36

def return_valid(cnpj, format: :masked)
  valid?(cnpj) ? format(cnpj, format: format) : ''
end

.valid?(cnpj) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/cnpj_tools.rb', line 8

def valid?(cnpj)
  tax_id = cnpj_to_s(cnpj)

  if tax_id.length == 14
    return false if invalid_repetition?(tax_id)

    id_array = tax_id.split('').map(&:to_i)

    first_digit  = id_multiplier(id_array[0..11])
    second_digit = id_multiplier(id_array[0..12])

    first_digit == id_array[12] && second_digit == id_array[13]
  else
    return false
  end
end