Class: CpfCnpjPlus::Generator::Cpf
- Inherits:
-
Object
- Object
- CpfCnpjPlus::Generator::Cpf
- Defined in:
- lib/cpf_cnpj_plus/generator/cpf.rb
Overview
Responsável por gerar números de CPF válidos aleatoriamente. Calcula os dígitos verificadores conforme o algoritmo oficial da Receita Federal.
Class Method Summary collapse
Class Method Details
.build_cpf(base) ⇒ Object
16 17 18 19 20 |
# File 'lib/cpf_cnpj_plus/generator/cpf.rb', line 16 def self.build_cpf(base) d1 = calculate_digit(base, (2..10).to_a.reverse) d2 = calculate_digit(base + [d1], (2..11).to_a.reverse) (base + [d1, d2]).join end |
.calculate_digit(digits, weights) ⇒ Object
22 23 24 25 26 |
# File 'lib/cpf_cnpj_plus/generator/cpf.rb', line 22 def self.calculate_digit(digits, weights) soma = digits.each_with_index.sum { |d, i| d * weights[i] } result = (soma * 10) % 11 result == 10 ? 0 : result end |
.generate ⇒ Object
8 9 10 11 12 13 14 |
# File 'lib/cpf_cnpj_plus/generator/cpf.rb', line 8 def self.generate loop do base = Array.new(9) { rand(0..9) } cpf = build_cpf(base) return cpf unless Validator::Cpf.cpf_not_valid?(cpf) end end |