Skip to content

Commit

Permalink
Adding chilean_id in Faker::IDNumber (faker-ruby#1819)
Browse files Browse the repository at this point in the history
* Adding chilean_id in Faker::IDNumber

* Referring to Faker::ChileRut in the id_number documentation
  • Loading branch information
cristofer authored and michebble committed Feb 16, 2020
1 parent 9fb4b49 commit 266e27c
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
6 changes: 5 additions & 1 deletion doc/default/id_number.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,8 @@ Faker::IDNumber.brazilian_citizen_number(formatted: true) #=> 000.000.000-00
# Keyword arguments: formatted
Faker::IDNumber.brazilian_id #=> 1212312312
Faker::IDNumber.brazilian_id(formatted: true) #=> 12.123.123-12
```

# Generate a Chilean ID (Rut with 8 digits)
# For more advanced cases, please refer to Faker::ChileRut
Faker::IDNumber.chilean_id #=> "15620613-K"
```
29 changes: 29 additions & 0 deletions lib/faker/default/id_number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class IDNumber < Base
BRAZILIAN_ID_FROM = 10_000_000
BRAZILIAN_ID_TO = 99_999_999

CHILEAN_MODULO = 11

class << self
def valid
_translate('valid')
Expand Down Expand Up @@ -105,8 +107,35 @@ def brazilian_id(legacy_formatted = NOT_GIVEN, formatted: false)

alias brazilian_rg brazilian_id

def chilean_id
digits = Faker::Number.number(digits: 8)
verification_code = chilean_verification_code(digits)

digits.to_s + '-' + verification_code.to_s
end

private

def chilean_verification_code(digits)
# First digit is multiplied by 3, second by 2, and so on
multiplication_rule = [3, 2, 7, 6, 5, 4, 3, 2]
digits_splitted = digits.to_s.chars.map(&:to_i)

sum = digits_splitted.map.with_index { |digit, index| digit * multiplication_rule[index] }.reduce(:+)

modulo = sum.modulo(CHILEAN_MODULO)
difference = CHILEAN_MODULO - modulo

case difference
when 0..9
difference
when 10
'K'
when 11
0
end
end

def south_african_id_checksum_digit(id_number)
value_parts = id_number.chars
even_digits = value_parts
Expand Down
17 changes: 17 additions & 0 deletions test/faker/default/test_faker_id_number.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,23 @@ def test_brazilian_id_digit
assert_equal digit_other, '9'
end

def test_chilean_id
sample = @tester.chilean_id
assert_match(/^\d{8}-[K\d]$/, sample)
end

def test_chilean_verification_code_k
verification_code = Faker::IDNumber.send(:chilean_verification_code, 20_680_873)

assert_equal verification_code, 'K'
end

def test_chilean_verification_code_0
verification_code = Faker::IDNumber.send(:chilean_verification_code, 13_196_022)

assert_equal verification_code, 0
end

private

def south_african_id_number_to_date_of_birth_string(sample)
Expand Down

0 comments on commit 266e27c

Please sign in to comment.