Created
November 23, 2010 13:04
-
-
Save joona/711719 to your computer and use it in GitHub Desktop.
quick hack for BBAN <=> IBAN conversion for Finnish bank account numbers, attached to String-class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$BANK_PREFIXES = [1, 2, 31, 33, 34, 36, 37, 38, 39, 4, 5, 6, 8] | |
class String | |
# converts bank account to numeric format | |
def to_account | |
if self.include?('-') | |
return self.sub(/\-(\d)(\d+)$/, "\\1" << '0' * ((14 - self.length)+1) << "\\2").to_i if ['4','5'].include?(self[0..0]) | |
return self.sub('-', '0' * ((14 - self.length) + 1)).to_i | |
end | |
self.to_i | |
end | |
# converts Finnish bank account number to IBAN | |
def to_iban | |
hash = 98 - ((self.to_account.to_s + '151800').to_i % 97) | |
"FI%02d%d" % [hash, self.to_account] | |
end | |
# converts Finnish IBAN account to numeric BBAN | |
def to_bban | |
return self[4..-1].to_i if self.include?('FI') | |
self.to_i | |
end | |
# validate IBAN | |
def valid_iban? | |
(("%s%s" % [self[4..-1], self[0..3]]).sub('FI', '1518').to_i % 97) == 1 | |
end | |
# validate BBAN | |
def valid_bban? | |
return false if $BANK_PREFIXES.reject {|x| x unless self =~ /^#{x}/ }.nitems == 0 | |
self.to_bban.to_s[-1..-1].to_i == self.to_bban.to_s[0..-2].split('').reverse.enum_for(:each_with_index).collect { |o, i| o.to_i*[2,1][i%2] }.to_s.split('').inject(0){|s, i| s - i.to_i } % 10 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
comment ca se passe bien ?tous va au mieux?