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/
VALIDATION_SIZE_REGEX =
/^[0-9]{11}$/
NUMBER_SIZE =
9
BLACKLIST =
%w[
  00000000000
  11111111111
  22222222222
  33333333333
  44444444444
  55555555555
  66666666666
  77777777777
  88888888888
  99999999999
  12345678909
  01234567890
].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.



40
41
42
43
# File 'lib/cpf.rb', line 40

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/cpf.rb', line 8

def number
  @number
end

#strictObject (readonly)

Returns the value of attribute strict.



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

def strict
  @strict
end

Class Method Details

.generate(formatted = false) ⇒ Object



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

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)


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

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

Instance Method Details

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



71
72
73
# File 'lib/cpf.rb', line 71

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

#formattedObject



56
57
58
# File 'lib/cpf.rb', line 56

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

#strippedObject



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

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

#valid?Boolean

Returns:

  • (Boolean)


60
61
62
63
64
65
66
67
68
69
# File 'lib/cpf.rb', line 60

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

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

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