Sha256: e50556076b78bf3cb947898b0350c9172559882b51f2b5405d21f506540b19cb

Contents?: true

Size: 872 Bytes

Versions: 11

Compression:

Stored size: 872 Bytes

Contents

class CusipValidator < ActiveModel::EachValidator

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

  private

  def valid_format?(value)
    value =~ /^[0-9A-Z]{9}$/
  end

  def valid_checksum?(value)
    digits      = value.split('').map { |i| i.match(/[A-Z]/) ? (i.ord - 55) : i.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) do |sum, i|
      sum += (i / 10) + i % 10
    end

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

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

end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
flash_validators-3.0.12 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.11 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.10 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.9 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.8 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.7 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.6 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.5 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.4 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.3 lib/flash_validators/validators/cusip_validator.rb
flash_validators-3.0.2 lib/flash_validators/validators/cusip_validator.rb