Class: MiniDefender::Rules::Iban

Inherits:
MiniDefender::Rule show all
Defined in:
lib/mini_defender/rules/iban.rb

Constant Summary collapse

LENGTH_MATRIX =
{
  'SA' => 24
}
REPLACEMENTS =
{
  'A' => '10', 'B' => '11', 'C' => '12', 'D' => '13', 'E' => '14', 'F' => '15',
  'G' => '16', 'H' => '17', 'I' => '18', 'J' => '19', 'K' => '20', 'L' => '21',
  'M' => '22', 'N' => '23', 'O' => '24', 'P' => '25', 'Q' => '26', 'R' => '27',
  'S' => '28', 'T' => '29', 'U' => '30', 'V' => '31', 'W' => '32', 'X' => '33',
  'Y' => '34', 'Z' => '35'
}

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from MiniDefender::Rule

#active?, available?, #bails?, #default_value, #defaults?, #error_message, #excluded?, #force_coerce?, #implicit?, make, #priority, #stops?, #with_message

Class Method Details

.signatureObject



16
17
18
# File 'lib/mini_defender/rules/iban.rb', line 16

def self.signature
  'iban'
end

Instance Method Details

#coerce(value) ⇒ Object



20
21
22
# File 'lib/mini_defender/rules/iban.rb', line 20

def coerce(value)
  value.to_s.upcase.gsub(/\s/, '')
end

#message(attribute, value, validator) ⇒ Object



39
40
41
# File 'lib/mini_defender/rules/iban.rb', line 39

def message(attribute, value, validator)
  "The value should be a valid IBAN."
end

#passes?(attribute, value, validator) ⇒ Boolean

Returns:



24
25
26
27
# File 'lib/mini_defender/rules/iban.rb', line 24

def passes?(attribute, value, validator)
  value = coerce(value)
  value.match?(/[A-Z]{2}\d+/i) && valid_length?(value) && valid_checksum?(value)
end

#valid_checksum?(iban) ⇒ Boolean

Returns:



29
30
31
32
33
# File 'lib/mini_defender/rules/iban.rb', line 29

def valid_checksum?(iban)
  iban = "#{iban[4..]}#{iban[0..1]}#{iban[2..3]}"
  iban = iban.gsub(Regexp.union(REPLACEMENTS.keys), REPLACEMENTS)
  iban.to_i % 97 === 1
end

#valid_length?(iban) ⇒ Boolean

Returns:



35
36
37
# File 'lib/mini_defender/rules/iban.rb', line 35

def valid_length?(iban)
  iban.length == (LENGTH_MATRIX[iban[0..1]] || iban.length)
end