Skip to content

Instantly share code, notes, and snippets.

@onnimonni
Last active October 21, 2017 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onnimonni/7e50d3fe0a52c171005b211c27682650 to your computer and use it in GitHub Desktop.
Save onnimonni/7e50d3fe0a52c171005b211c27682650 to your computer and use it in GitHub Desktop.
Ruby class for generating valid fake IBAN numbers for testing
# Module for generating random Iban account numbers
module IBAN
# Calculates the mandatory checksum of 3..4 characters in iban
def iban_checksum(account, cc)
# Converts letters to numbers according the iban rules, A=10..Z=35
iban_to_num = "#{account}#{cc}00".upcase.chars.map { |d|
d.match(/[A-Z]/) ? (d.ord - 55).to_s : d
}.join.to_i
# Calculate checksum with reverse modulo
# This is answer to (iban_to_num + checksum) % 97 == 1
checksum = ( 1 - iban_to_num ) % 97
# Use leftpad to make it's size always 2
checksum.to_s.rjust(2, '0')
end
def generate_iban(size: 20, cc: 'GB', account: '')
# Generate random account of size if it's not given
account = (size - 4).times.map { rand(0..9) }.join if account.empty?
# Return in iban format
cc + iban_checksum(account,cc) + account
end
end
20.times { puts IBAN::generate(size: 18, cc: 'FI') }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment