Skip to content

Instantly share code, notes, and snippets.

@frznk-tank
Last active June 25, 2018 13:13
Show Gist options
  • Save frznk-tank/af1e3c3dba1627451abc8552a5e99baf to your computer and use it in GitHub Desktop.
Save frznk-tank/af1e3c3dba1627451abc8552a5e99baf to your computer and use it in GitHub Desktop.
Ruby random South African ID number generator
def id_number(birthday, gender)
gender = (0..4).to_a.sample if gender == 'female'
gender = (5..9).to_a.sample if gender == 'male'
random_sequence = rand.to_s[2..5]
citizenship = 0
race = 8
id_number = [
birthday.gsub('-', '')[2..-1],
gender,
random_sequence,
citizenship,
race
].join.split('').map(&:to_i)
# Luhn digit
luhn_total = 0
luhn_count = 0
id_number.each do |d, x|
multiple = (luhn_count % 2) + 1
luhn_count += 1
temp = multiple * d
luhn_total += (temp/10).floor + (temp % 10)
end
return id_number.push((luhn_total * 9) % 10).join
end
class ZaIdNumberValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if value.length != 13
record.errors[attribute] << (options[:message] || "Identification number is invalid")
else
id_number = value.to_s.split('').map(&:to_i)
luhn_check = id_number.last
luhn_total = 0
luhn_count = 0
id_number.take(12).each do |d, x|
multiple = (luhn_count % 2) + 1
luhn_count += 1
temp = multiple * d
luhn_total += (temp/10).floor + (temp % 10)
end
if luhn_check != (luhn_total * 9) % 10
record.errors[attribute] << (options[:message] || "Identification number is invalid")
end
end
end
end
class Profile < ApplicationRecord
validates :identification_number,
presence: true,
za_id_number: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment