Sha256: c768e2a6531919dcc606a4770753c3a617dcccf47420a3a5a732f16a60c030e4

Contents?: true

Size: 1019 Bytes

Versions: 3

Compression:

Stored size: 1019 Bytes

Contents

class CusipValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    return if valid?(value.to_s)
    record.errors[attribute] <<
      (options[:message] || I18n.t('active_validation.errors.messages.cusip'))
  end

  private

  # rubocop:disable Lint/UselessAssignment
  def valid_checksum?(value)
    digits = value.chars.map { |chr| /[A-Z]/.match?(chr) ? (chr.ord - 55) : chr.to_i }
    even_values = digits.values_at(* digits.each_index.select(&:even?))
    odd_values = digits.values_at(* digits.each_index.select(&:odd?))
    values = odd_values.map { |int| int * 2 }.zip(even_values).flatten
    values = values.inject(0) { |sum, int| sum += (int / 10) + int % 10 }

    ((10 - values) % 10) % 10
  end
  # rubocop:enable Lint/UselessAssignment

  def valid_format?(value)
    value =~ /^[0-9A-Z]{9}$/
  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

3 entries across 3 versions & 1 rubygems

Version Path
active_validation-4.0.11 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.10 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.9 lib/active_validation/validators/cusip_validator.rb