Class: VinUtils::Validator

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

Constant Summary collapse

DIGIT_BASE =
%w[0 1 2 3 4 5 6 7 8 9 . A B C D E F G H . . J K L M N . P . R . . S T U V W X Y Z].freeze
MAP =
%w[0 1 2 3 4 5 6 7 8 9 X].freeze
WEIGHTS =
[8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vin) ⇒ Validator



9
10
11
12
# File 'lib/vin_utils/validator.rb', line 9

def initialize(vin)
  @vin = vin
  @vin = @vin.upcase if @vin.instance_of?(String)
end

Instance Attribute Details

#vinObject

Returns the value of attribute vin.



3
4
5
# File 'lib/vin_utils/validator.rb', line 3

def vin
  @vin
end

Instance Method Details

#calculate_check_digitObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/vin_utils/validator.rb', line 20

def calculate_check_digit
  return :invalid unless valid_input?

  sum = 0
  @vin.chars.each_with_index do |char, i|
    sum += transliterate(char) * WEIGHTS[i]
  end

  MAP[sum % 11]
end

#suggest_valid_vinObject



31
32
33
34
35
36
37
38
# File 'lib/vin_utils/validator.rb', line 31

def suggest_valid_vin
  return :invalid unless valid_input?
  return @vin if valid?

  new_vin = @vin.dup
  new_vin[8] = calculate_check_digit
  new_vin
end

#valid?Boolean



14
15
16
17
18
# File 'lib/vin_utils/validator.rb', line 14

def valid?
  return false unless valid_input?

  calculate_check_digit == @vin[8]
end