Sha256: 4ca99613bc75986865e329bc6d4aeda17698510c4760386048b3c3d0e9e41b2c

Contents?: true

Size: 973 Bytes

Versions: 5

Compression:

Stored size: 973 Bytes

Contents

class CusipValidator < ActiveModel::EachValidator

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

  private

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

    ((10 - values) % 10) % 10
  end

  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

5 entries across 5 versions & 1 rubygems

Version Path
active_validation-2.2.2 lib/active_validation/validators/cusip_validator.rb
active_validation-2.2.1 lib/active_validation/validators/cusip_validator.rb
active_validation-2.2.0 lib/active_validation/validators/cusip_validator.rb
active_validation-2.0.1 lib/active_validation/validators/cusip_validator.rb
active_validation-2.0.0 lib/active_validation/validators/cusip_validator.rb