class BankTools::Global::IBAN

Constants

E

Public Class Methods

new(raw) click to toggle source
# File lib/banktools/global/iban.rb, line 9
def initialize(raw)
  @pre_normalized = raw.to_s.gsub(/\s/, "").strip.upcase
end

Public Instance Methods

errors() click to toggle source
# File lib/banktools/global/iban.rb, line 17
def errors
  rule = rules[country_code]
  return [ E::UNKNOWN_COUNTRY ] unless rule

  length = rule.fetch("length")
  return [ E::WRONG_LENGTH ] unless @pre_normalized.length == length

  re = rule.fetch("bban_pattern")
  return [ E::BAD_FORMAT ] unless bban.match?(re)

  return [ E::BAD_CHECKSUM ] unless good_checksum?

  []
end
normalize() click to toggle source
# File lib/banktools/global/iban.rb, line 32
def normalize
   @pre_normalized.gsub(/.{4}/, '\0 ').strip
end
valid?() click to toggle source
# File lib/banktools/global/iban.rb, line 13
def valid?
  errors.empty?
end

Private Instance Methods

bban() click to toggle source
# File lib/banktools/global/iban.rb, line 59
def bban
  @pre_normalized[4..-1]
end
check_digits() click to toggle source
# File lib/banktools/global/iban.rb, line 55
def check_digits
  @pre_normalized[2..3]
end
country_code() click to toggle source
# File lib/banktools/global/iban.rb, line 51
def country_code
  @pre_normalized[0..1]
end
good_checksum?() click to toggle source
# File lib/banktools/global/iban.rb, line 38
def good_checksum?
  number_string =
    (bban + country_code + check_digits).chars.map { |char|
      case char
      when "0".."9" then char
      when "A".."Z" then (char.ord - 55).to_s
      else raise "Unexpected byte '#{byte}' in IBAN '#{normalize}'!"
      end
    }.join

  number_string.to_i % 97 == 1
end
rules() click to toggle source
# File lib/banktools/global/iban.rb, line 63
def rules
  @@rules ||=
    YAML.load(File.read(File.join(File.dirname(__FILE__), "iban_rules.yml")))
      .transform_values { |h| h.merge("bban_pattern" => /\A#{h.fetch("bban_pattern")}\z/) }
end