class SedolValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless valid?(value) record.errors[attribute] << (options[:message] || I18n.t('errors.messages.sedol')) end end private def valid_format?(value) value =~ /^([A-Z0-9]{6})(\d{1})$/ end def valid_checksum?(value) digits = value.split('').map { |i| i.match(/[A-Z]/) ? (i.ord - 55) : i.to_i } weights = [1, 3, 1, 7, 3, 9, 1] sum = 0 digits.each_with_index do |i, idx| sum += weights[idx] * i end (10 - sum % 10) % 10 end def valid?(value) valid_format?(value) && valid_checksum?(value) end end