Sha256: de74fcd375068123f2c446bb377600932ea1ff69a2b50b7e54f9a5c443d32b09

Contents?: true

Size: 669 Bytes

Versions: 2

Compression:

Stored size: 669 Bytes

Contents

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
flash_validators-3.0.1 lib/flash_validators/validators/sedol_validator.rb
flash_validators-3.0.0 lib/flash_validators/validators/sedol_validator.rb