Class: CNPJ

Inherits:
Object
  • Object
show all
Defined in:
lib/cnpj.rb,
lib/cnpj/formatter.rb,
lib/cpf_cnpj/version.rb,
lib/cnpj/verifier_digit.rb

Defined Under Namespace

Classes: Formatter, VerifierDigit

Constant Summary collapse

REGEX =
%r[\A\d{2}\.\d{3}.\d{3}/\d{4}-\d{2}\Z]
VALIDATION_SIZE_REGEX =
/^\d{14}$/
NUMBER_SIZE =
12
BLACKLIST =
%w[
  00000000000000
  11111111111111
  22222222222222
  33333333333333
  44444444444444
  55555555555555
  66666666666666
  77777777777777
  88888888888888
  99999999999999
].freeze
VERSION =
CpfCnpj::VERSION

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number, strict = false) ⇒ CNPJ

Returns a new instance of CNPJ.



38
39
40
41
# File 'lib/cnpj.rb', line 38

def initialize(number, strict = false)
  @number = number.to_s
  @strict = strict
end

Instance Attribute Details

#numberObject

Returns the value of attribute number.



8
9
10
# File 'lib/cnpj.rb', line 8

def number
  @number
end

#strictObject (readonly)

Returns the value of attribute strict.



9
10
11
# File 'lib/cnpj.rb', line 9

def strict
  @strict
end

Class Method Details

.generate(formatted = false) ⇒ Object



32
33
34
35
36
# File 'lib/cnpj.rb', line 32

def self.generate(formatted = false)
  number = CpfCnpj::Generator.generate(NUMBER_SIZE, VerifierDigit)
  cnpj = new(number)
  formatted ? cnpj.formatted : cnpj.stripped
end

.valid?(number, strict: false) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/cnpj.rb', line 28

def self.valid?(number, strict: false)
  new(number, strict).valid?
end

Instance Method Details

#==(object) ⇒ Object Also known as: eql?



69
70
71
# File 'lib/cnpj.rb', line 69

def ==(object)
  super || object.instance_of?(self.class) && object.stripped == stripped
end

#formattedObject



54
55
56
# File 'lib/cnpj.rb', line 54

def formatted
  @formatted ||= Formatter.format(number)
end

#strippedObject



50
51
52
# File 'lib/cnpj.rb', line 50

def stripped
  @stripped ||= Formatter.strip(number, strict)
end

#valid?Boolean

Returns:

  • (Boolean)


58
59
60
61
62
63
64
65
66
67
# File 'lib/cnpj.rb', line 58

def valid?
  return unless stripped =~ VALIDATION_SIZE_REGEX
  return if BLACKLIST.include?(stripped)

  digits = numbers[0...12]
  digits << VerifierDigit.generate(digits)
  digits << VerifierDigit.generate(digits)

  digits[-2, 2] == numbers[-2, 2]
end