Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

including brazilian cpf #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions lib/id_number_latam/br_cpf.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
module IdNumberLatam
class BrCPF < Base
# This Class allows validating the Argentinean Number (DNI).
# This document does not have a verification digit.

def initialize(id_number, opts = {})
super
@country = :br
@digit = unformat[-2..-1]
end

def unformat
id_number.gsub(/\D/, "")
end

def format
cpf = unformat
groups = cpf.match(/(\d{3})(\d{3})(\d{3})(\d{2})/)[1..-1]
formatted_cpf="%s.%s.%s-%s" % groups
end

def valid?
return false unless valid_length
cpf = unformat
digits = (cpf[-2..-1]).to_i
first_slice, second_slice = cpf[0..-3], cpf[0..-2]
pre_calc_lambda = lambda { |x, str| str.chars.each_with_index.reduce(0) { |acc, (d, i)| (acc += d.to_i*(x-i)) } }
first_digit = pre_calc_lambda.call(10, first_slice) * 10 % 11
first_digit = first_digit == 10 ? 0 : first_digit
second_digit = pre_calc_lambda.call(11, second_slice) * 10 % 11
verification_digits = ("%s%s" % [first_digit, second_digit]).to_i
return true unless verification_digits != digits
end

def valid_length
unformat.size == 11
end

end
end
19 changes: 19 additions & 0 deletions spec/id_number_latam/br_cpf_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# frozen_string_literal: true

RSpec.describe IdNumberLatam::BrCPF do
subject { described_class.new("529.982.247-25") }

context "with a valid id number" do
it "valid id_number" do
expect(subject.valid?).to be_truthy
end

it "unformat id_number" do
expect(subject.unformat).to eq("52998224725")
end

it "format id_number" do
expect(subject.format).to eq("529.982.247-25")
end
end
end