module ContainerNumberValidator

Constants

LETTERS
VERSION
WEIGHTS

Public Class Methods

calculate_checksum(container_no) click to toggle source
# File lib/container_number_validator.rb, line 46
def calculate_checksum(container_no)
  chars = container_no.chars
  digits, weights = [], []

  chars[0..3].each  { |char| digits << LETTERS[char.upcase] }
  chars[4..10].each { |char| digits << char }

  digits.each_with_index do |digit, i|
    weights[i] = digit.to_i * WEIGHTS[i].to_i
  end

  checksum = weights.reduce(:+) % 11

  # When checksum equals 10 the last digit will equal 0
  checksum == 10 ? 0 : checksum
end
validate(container_no) click to toggle source
# File lib/container_number_validator.rb, line 34
def validate(container_no)
  return false unless container_no.to_s =~ /^[a-zA-Z]{4}\d{6}\-?\d$/

  checksum = container_no[-1, 1].to_i
  number   = container_no[0..-1]

  calculate_checksum(number) == checksum
end

Private Instance Methods

calculate_checksum(container_no) click to toggle source
# File lib/container_number_validator.rb, line 46
def calculate_checksum(container_no)
  chars = container_no.chars
  digits, weights = [], []

  chars[0..3].each  { |char| digits << LETTERS[char.upcase] }
  chars[4..10].each { |char| digits << char }

  digits.each_with_index do |digit, i|
    weights[i] = digit.to_i * WEIGHTS[i].to_i
  end

  checksum = weights.reduce(:+) % 11

  # When checksum equals 10 the last digit will equal 0
  checksum == 10 ? 0 : checksum
end
validate(container_no) click to toggle source
# File lib/container_number_validator.rb, line 34
def validate(container_no)
  return false unless container_no.to_s =~ /^[a-zA-Z]{4}\d{6}\-?\d$/

  checksum = container_no[-1, 1].to_i
  number   = container_no[0..-1]

  calculate_checksum(number) == checksum
end