Sha256: 8f3284e38646ba497542ce6130d2cacc42dd3356f07687dfc94937e525354a8f

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

module PersonPin
  class Egn
    def self.valid?(egn)
      (egn.length == 10) && (calculate_control_digit(egn[0..8]) == egn[9].to_i)
    end

    def self.gender(egn)
      gender_digit = egn.split('')[8].to_i % 2
      gender_digit.zero? ? 'male' : 'female'
    end

    def self.random
      year = rand(1900..1920)
      month = rand(1..12)
      day = rand(1..28)
      daily(year, month, day)[rand(0..999)]
    end

    def self.daily(year, month, day)
      month += 40 if year >= 2000
      year_s = (year % 100).to_s.rjust(2, '0')
      month_s = month.to_s.rjust(2, '0')
      day_s = day.to_s.rjust(2, '0')
      base = year_s + month_s + day_s
      results = []
      1000.times do |sequence|
        egn = base + sequence.to_s.rjust(3, '0')
        egn[9] = calculate_control_digit(egn).to_s
        results << egn
      end
      results
    end

    def self.calculate_control_digit(egn)
      weights = [2, 4, 8, 5, 10, 9, 7, 3, 6]
      sum = 0
      egn.split('').each_with_index do |digit, index|
        sum += digit.to_i * weights[index]
      end
      control_digit = sum % 11
      control_digit == 10 ? 0 : control_digit
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
person_pin-0.1.0 lib/person_pin/egn.rb