Class: Ibanify::IBAN

Inherits:
Object
  • Object
show all
Defined in:
lib/ibanify.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number) ⇒ IBAN

Returns a new instance of IBAN.



7
8
9
# File 'lib/ibanify.rb', line 7

def initialize(number)
  @number = IBAN.normalize(number)
end

Class Method Details

.normalize(number) ⇒ Object



56
57
58
# File 'lib/ibanify.rb', line 56

def self.normalize(number)
  number.strip.gsub(/\s+/, '').upcase
end

.valid?(number) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/ibanify.rb', line 11

def self.valid?(number)
  new(number).validation_error.nil?
end

Instance Method Details

#bbanObject



39
40
41
# File 'lib/ibanify.rb', line 39

def bban
  @number[4..-1]
end

#countriesObject



43
44
45
# File 'lib/ibanify.rb', line 43

def countries
  load_countries_from_string(File.read(File.dirname(__FILE__) + '/ibanify/countries.yml'))
end

#country_codeObject



35
36
37
# File 'lib/ibanify.rb', line 35

def country_code
  @number[0..1]
end

#load_countries_from_string(string) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/ibanify.rb', line 47

def load_countries_from_string(string)
  hash = YAML.load(string)
  hash.each do |country_code, rules|
    rules['bban'] = Regexp.new('^' + rules['bban'] + '$')
  end

  Countries.new(hash)
end

#numberObject



31
32
33
# File 'lib/ibanify.rb', line 31

def number
  @number
end

#valid_check_digits?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
# File 'lib/ibanify.rb', line 22

def valid_check_digits?
  iban = @number[4..-1] + @number[0, 4]
  iban.gsub!(/./) do |c|
    c.to_i(36)
  end
 
  iban.to_i % 97 == 1
end

#validation_errorObject



15
16
17
18
19
20
# File 'lib/ibanify.rb', line 15

def validation_error
  return :invalid_country_code unless countries[country_code]
  return :invalid_length       unless countries[country_code]['length'] == @number.size
  return :invalid_bban         unless bban =~ countries[country_code]['bban']
  return :invalid_check_digits unless valid_check_digits?
end