lib/vindetta/validator.rb in vindetta-0.15.0 vs lib/vindetta/validator.rb in vindetta-0.16.0

- old
+ new

@@ -1,17 +1,23 @@ -require "active_model" - module Vindetta - class Validator < ActiveModel::Validator + class Validator LENGTH = 17 + CHECK_DIGIT_INDEX = 8 + MAP = "0123456789X".chars + WEIGHTS = "8765432X098765432".chars def self.run(value) - Vin.new(value).valid? + return false unless value.length == LENGTH + + check_digit(value) == value[CHECK_DIGIT_INDEX] end - def validate(record) - record.errors.add(:value, I18n.t("invalid_length")) if record.value.length != LENGTH + def self.check_digit(value) + check_digit = value.chars[8] + calculated = value.chars.map.with_index do |c, i| + Transliterator::run(c) * MAP.find_index(WEIGHTS[i]) + end.sum - # TODO: Check format + MAP[calculated % 11] end end end