diff --git a/doc/default/id_number.md b/doc/default/id_number.md index b453fee370..04bb62a730 100644 --- a/doc/default/id_number.md +++ b/doc/default/id_number.md @@ -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" +``` \ No newline at end of file diff --git a/lib/faker/default/id_number.rb b/lib/faker/default/id_number.rb index 0bc664198b..7a357ee894 100644 --- a/lib/faker/default/id_number.rb +++ b/lib/faker/default/id_number.rb @@ -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') @@ -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 diff --git a/test/faker/default/test_faker_id_number.rb b/test/faker/default/test_faker_id_number.rb index 4e67c1fc99..d52e815b98 100644 --- a/test/faker/default/test_faker_id_number.rb +++ b/test/faker/default/test_faker_id_number.rb @@ -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)