Sha256: a3d4b214a848b467a2b44d39b98464816c2bef3cd6b6e36a6b6375a3499a3b4a

Contents?: true

Size: 1014 Bytes

Versions: 8

Compression:

Stored size: 1014 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| chr =~ /[A-Z]/ ? (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

8 entries across 8 versions & 1 rubygems

Version Path
active_validation-4.0.8 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.7 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.6 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.5 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.4 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.3 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.2 lib/active_validation/validators/cusip_validator.rb
active_validation-4.0.1 lib/active_validation/validators/cusip_validator.rb