Sha256: bf5388a3dabfeff1e991c23ed5c8e8024597a5ff2c25d8fdb739c5fedf9fa888

Contents?: true

Size: 788 Bytes

Versions: 4

Compression:

Stored size: 788 Bytes

Contents

class SedolValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    unless valid?(value.to_s)
      record.errors[attribute] << (options.fetch(:message, false) || I18n.t('active_validation.errors.messages.sedol'.freeze))
    end
  end

  private

  def valid_checksum?(value)
    digits  = value.chars.map { |d| d.match(/[A-Z]/) ? (d.ord - 55) : d.to_i }
    weights = [1, 3, 1, 7, 3, 9, 1].freeze

    total = 0
    digits.lazy.each_with_index { |d, i| total += (weights[i] * d) }

    (10 - total % 10) % 10
  end

  def valid_format?(value)
    value =~ /^([A-Z0-9]{6})(\d{1})$/
  end

  def valid_length?(value)
    value.present?
  end

  def valid?(value)
    valid_length?(value) &&
    valid_format?(value) &&
    valid_checksum?(value)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_validation-2.6.0 lib/active_validation/validators/sedol_validator.rb
active_validation-2.5.0 lib/active_validation/validators/sedol_validator.rb
active_validation-2.4.0 lib/active_validation/validators/sedol_validator.rb
active_validation-2.3.0 lib/active_validation/validators/sedol_validator.rb