Class: CPF

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

Defined Under Namespace

Classes: Formatter, VerifierDigit

Constant Summary collapse

REGEX =
/\A\d{3}\.\d{3}\.\d{3}-\d{2}\Z/
NUMBER_SIZE =
9
BLACKLIST =
%w[
  00000000000
  11111111111
  22222222222
  33333333333
  44444444444
  55555555555
  66666666666
  77777777777
  88888888888
  99999999999
  12345678909
].freeze
VERSION =
CpfCnpj::VERSION

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number, strict = false) ⇒ CPF

Returns a new instance of CPF.



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

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

Instance Attribute Details

#numberObject

Returns the value of attribute number.



6
7
8
# File 'lib/cpf.rb', line 6

def number
  @number
end

#strictObject (readonly)

Returns the value of attribute strict.



7
8
9
# File 'lib/cpf.rb', line 7

def strict
  @strict
end

Class Method Details

.generate(formatted = false) ⇒ Object



30
31
32
33
34
# File 'lib/cpf.rb', line 30

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

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

Returns:

  • (Boolean)


26
27
28
# File 'lib/cpf.rb', line 26

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

Instance Method Details

#formattedObject



52
53
54
# File 'lib/cpf.rb', line 52

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

#strippedObject



48
49
50
# File 'lib/cpf.rb', line 48

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

#valid?(strict: false) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
59
60
61
62
63
64
65
# File 'lib/cpf.rb', line 56

def valid?(strict: false)
  return unless stripped.size == 11
  return if BLACKLIST.include?(stripped)

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

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