Class: CpfCnpjPlus::Generator::Cnpj
- Inherits:
-
Object
- Object
- CpfCnpjPlus::Generator::Cnpj
- Defined in:
- lib/cpf_cnpj_plus/generator/cnpj.rb
Overview
Responsável por gerar números de CNPJ válidos aleatoriamente. Suporta geração no formato numérico tradicional e no novo formato alfanumérico, calculando os dígitos verificadores conforme a Receita Federal.
Constant Summary collapse
- DIGITS =
("0".."9").to_a.freeze
- LETTERS =
("A".."Z").to_a.freeze
- ALPHANUMERIC =
(DIGITS + LETTERS).freeze
- WEIGHTS_1D =
[5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2].freeze
- WEIGHTS_2D =
[6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2].freeze
Class Method Summary collapse
- .build_base(alphanumeric) ⇒ Object
- .build_cnpj(base) ⇒ Object
- .calculate_digit(values, weights) ⇒ Object
- .char_to_value(char) ⇒ Object
- .generate(alphanumeric: false) ⇒ Object
Class Method Details
.build_base(alphanumeric) ⇒ Object
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/cpf_cnpj_plus/generator/cnpj.rb', line 24 def self.build_base(alphanumeric) if alphanumeric # Garante ao menos uma letra para ser genuinamente alfanumérico base = Array.new(12) { ALPHANUMERIC.sample } base[rand(0..11)] = LETTERS.sample base else Array.new(12) { DIGITS.sample } end end |
.build_cnpj(base) ⇒ Object
35 36 37 38 39 40 |
# File 'lib/cpf_cnpj_plus/generator/cnpj.rb', line 35 def self.build_cnpj(base) values = base.map { |c| char_to_value(c) } d1 = calculate_digit(values, WEIGHTS_1D) d2 = calculate_digit(values + [d1], WEIGHTS_2D) base.join + "#{d1}#{d2}" end |
.calculate_digit(values, weights) ⇒ Object
46 47 48 49 50 |
# File 'lib/cpf_cnpj_plus/generator/cnpj.rb', line 46 def self.calculate_digit(values, weights) soma = weights.each_with_index.sum { |w, i| values[i] * w } result = (soma * 10) % 11 result == 10 ? 0 : result end |
.char_to_value(char) ⇒ Object
42 43 44 |
# File 'lib/cpf_cnpj_plus/generator/cnpj.rb', line 42 def self.char_to_value(char) char.ord - 48 end |
.generate(alphanumeric: false) ⇒ Object
16 17 18 19 20 21 22 |
# File 'lib/cpf_cnpj_plus/generator/cnpj.rb', line 16 def self.generate(alphanumeric: false) loop do base = build_base(alphanumeric) cnpj = build_cnpj(base) return cnpj unless Validator::Cnpj.cnpj_not_valid?(cnpj) end end |