Skip to content

Instantly share code, notes, and snippets.

@defkode
Created November 16, 2011 09:42
Show Gist options
  • Save defkode/499f9e3adf3b7f8a08f6 to your computer and use it in GitHub Desktop.
Save defkode/499f9e3adf3b7f8a08f6 to your computer and use it in GitHub Desktop.
machine_readable_code_validation
# TPD<<T220001293<<<<<<<<<<<<<<<
# 6408125<2010315D<<<<<<<<<<<<<4
# MUSTERMAN<<ERIKA<<<<<<<<<<<<<<
class PersonalId
attr_reader :code, :data
# 9 alphanumeric
def initialize(machinecode = "TPD<<2406055684D<<<<<<<<<<<<<<6810203<0705109D<<<<<<<<<<<<<6MUSTERMAN<<ERIKA<<<<<<<<<<<<<<")
@code = machinecode
@data = {
# line 1
:type => @code[0..2],
:id => @code[5..13],
:check_a => @code.at(14),
# line 2
:date_of_birth => @code[30...36],
:check_b => @code.at(36),
:expires_at => @code[38...44],
:check_c => @code.at(44),
:nationality => @code.at(45),
:check_d => @code.at(59),
# line 3
:name => @code[60...90]
}
end
def full_name
data[:name].sub("<<", " ").gsub("<", "")
end
def p1
to_digits(data[:id] + data[:check_a])
end
def p2
to_digits(data[:date_of_birth] + data[:check_b])
end
def p3
to_digits(data[:expires_at] + data[:check_c])
end
def to_digits(string)
string.split("").map(&:to_i)
end
def checksum_a
checksum(p1[0...-1])
end
def checksum_b
checksum(p2[0...-1])
end
def checksum_c
checksum(p3[0...-1])
end
def checksum_d
checksum([ p1, p2, p3 ].flatten)
end
def checksum(digits, i = 1)
digits.map do |digit|
wage = case (i % 3)
when 1 then 7
when 2 then 3
when 0 then 1
end
i += 1
digit * wage
end.sum
end
def valid?
(checksum_a == data[:check_a].to_i) && (checksum_b == data[:check_b].to_i) && (checksum_c == data[:check_c].to_i) && (checksum_d == data[:check_d].to_i)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment