class NhsNumberValidator

Public Class Methods

valid?(number) click to toggle source
# File lib/nhs_number_validator.rb, line 2
def self.valid?(number)
  if self.format_valid?(number)
    digit_array = number.to_s.split(//)
    if digit_array[9].to_i == check_digit(digit_array)
      true
    else
      false
    end
  else
    false
  end
end

Private Class Methods

check_digit(digit_array) click to toggle source
# File lib/nhs_number_validator.rb, line 25
def self.check_digit(digit_array)
  result_array = []
  Array(0..8).each do |i|
    result_array << ((11 - (i + 1)) * digit_array[i].to_i)
  end
  if (11 - (result_array.inject(:+) % 11)) == 10
    return false
  else
    return 0 if result_array.inject(:+) % 11 == 0
    return 11 - (result_array.inject(:+) % 11)
  end
end
format_valid?(number) click to toggle source
# File lib/nhs_number_validator.rb, line 21
def self.format_valid?(number)
  !!(/^\d{10}$/.match(number.to_s))
end

Public Instance Methods

validate_each(record, attribute, value) click to toggle source
# File lib/nhs_number_validator.rb, line 15
def validate_each(record, attribute, value)
  record.errors.add(attribute, options[:message] || :invalid) unless self.class.valid?(value)
end