Sha256: cc6ab9f0fa601732abea237be5707e63a69bfaec1eba2d0a5d667e66b8b3937c

Contents?: true

Size: 866 Bytes

Versions: 2

Compression:

Stored size: 866 Bytes

Contents

class CusipValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    unless valid?(value.to_s)
      record.errors[attribute] << (options[:message] || I18n.t('yukonisuru.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

2 entries across 2 versions & 1 rubygems

Version Path
yukonisuru-1.0.0 lib/yukonisuru/validators/cusip_validator.rb
yukonisuru-0.0.1 lib/yukonisuru/validators/cusip_validator.rb