Class: NationalIdentificationNumber::Swedish

Inherits:
Base
  • Object
show all
Defined in:
lib/national_identification_number/swedish.rb

Overview

Inspired by github.com/c7/personnummer/blob/master/lib/personnummer.rb Copyright © 2008 Peter Hellberg MIT

Instance Attribute Summary collapse

Class Method Summary collapse

Methods inherited from Base

#==, #age, #initialize, #sanitize, #to_s, #valid?

Constructor Details

This class inherits a constructor from NationalIdentificationNumber::Base

Instance Attribute Details

#dateObject (readonly)

used for testing



7
8
9
# File 'lib/national_identification_number/swedish.rb', line 7

def date
  @date
end

Class Method Details

.generate(date = nil, serial = nil) ⇒ Object

Generator for valid Swedish personnummer: en.wikipedia.org/wiki/Personal_identity_number_(Sweden) By Henrik Nyh <henrik.nyh.se> 2009-01-29 under the MIT license.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/national_identification_number/swedish.rb', line 11

def self.generate(date=nil, serial=nil)
  date ||= Date.new(1900+rand(100), 1+rand(12), 1+rand(28))
  serial = serial ? serial.to_s : format("%03d", rand(999)+1)  # 001-999
  date_part = date.strftime('%y%m%d')
  pnr = [date_part, serial].join
  digits = []
  pnr.split('').each_with_index do |n,i|
    digits << n.to_i * (2 - i % 2)
  end
  sum = digits.join.split('').inject(0) {|sum,digit| sum + digit.to_i }
  checksum = 10 - sum % 10
  checksum = 0 if checksum == 10
  "#{date_part}-#{serial}#{checksum}"
end