Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,39 @@ Then run `bundle install`
```ruby
require 'personnummer'

puts Personnummer.valid?("8507099805")
# => True
Personnummer.valid?("8507099805")
# => true

pnr = Personnummer.parse("198507099805")
pnr.format # => "850709-9805"
pnr.format(true) # => "198507099805"
pnr.get_date.to_s # => "1985-07-09"
pnr.get_age # => 41 (in 2026)
pnr.is_female? # => true
pnr.is_coord # => false
pnr.is_interim # => false
```

`parse` raises `Personnummer::Error` when the input is not a valid number.

### Options

`parse` and `valid?` take an options hash.

| Option | Default | Description |
| --------------------------- | ------- | ------------------------------------------------ |
| `allow_coordination_number` | `true` | Accept coordination numbers (samordningsnummer). |
| `allow_interim_number` | `false` | Accept interim numbers (T-numbers). |

```ruby
Personnummer.valid?("000101-T220")
# => false

Personnummer.valid?("000101-T220", allow_interim_number: true)
# => true

Personnummer.valid?("850769-9810", allow_coordination_number: false)
# => false
```

See [test/test_personnummer.rb](test/test_personnummer.rb) for more examples.
Expand Down
64 changes: 44 additions & 20 deletions lib/personnummer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@
require 'date'

module Personnummer
# Inherits from RuntimeError so existing `rescue RuntimeError` keeps working
class Error < RuntimeError; end

DEFAULT_OPTIONS = {
allow_coordination_number: true,
allow_interim_number: false
}.freeze

class Personnummer
def initialize(personnummer, options={})
parts = get_parts(personnummer)
Expand All @@ -13,10 +21,18 @@ def initialize(personnummer, options={})
attr_accessor k
end
end
@options = options
@options = DEFAULT_OPTIONS.merge(options || {})

if !valid
raise "Invalid Personnummer"
raise Error, "Invalid Personnummer"
end

if !@options[:allow_coordination_number] && is_coord
raise Error, "Coordination numbers are not allowed"
end

if !@options[:allow_interim_number] && is_interim
raise Error, "Interim numbers are not allowed"
end
end

Expand All @@ -26,6 +42,12 @@ def is_coord
test_date(full_year, @month.to_i, @day.to_i - 60)
end

# Checks if the Personnummer is an interim number (T-nummer)
# (TrueClass/FalseClass)
def is_interim
@num.match?(/\A[TRSUWXJKLMN]/)
end

# Returns the short/long formatted number
def format(long_format=false)
if long_format
Expand All @@ -39,16 +61,18 @@ def format(long_format=false)
# (Integer)
def get_age
today = Time.new
date = get_date

year = "#{@century}#{@year}".to_i
month = @month.to_i
day = @day.to_i
return today.year - date.year - ((today.month > date.month || (today.month == date.month && today.day >= date.day)) ? 0 : 1)
end

if is_coord
day -= 60
end
# Returns the date of birth, with the 60 day offset of coordination numbers removed
# (Date)
def get_date
day = @day.to_i
day -= 60 if is_coord

return today.year - year - ((today.month > month || (today.month == month && today.day >= day)) ? 0 : 1)
Date.new(full_year, @month.to_i, day)
end

# Checks if the Personnummer's owner is male
Expand All @@ -67,14 +91,14 @@ def is_female?
private

# Regex magic to split the input into parts hash.
# Raises error if regex is refused.
# Raises Error if regex is refused.
# (Hash)
def get_parts(personnummer)
reg = /(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\+\-]?)((?!000)\d{3})(\d)/;
reg = /\A(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\+\-]?)((?!000)\d{3}|[TRSUWXJKLMN]\d{2})(\d)\z/
match = personnummer.to_s.match(reg)

if !match
raise "Could not parse #{personnummer} as a valid Personnummer"
raise Error, "Could not parse #{personnummer} as a valid Personnummer"
end

century = match[1]
Expand Down Expand Up @@ -133,7 +157,7 @@ def valid
return false
end

is_valid = luhn(@year + @month + @day + @num) == @check.to_i
is_valid = luhn(@year + @month + @day + @num.sub(/\A[TRSUWXJKLMN]/, '1')) == @check.to_i

if is_valid && test_date(full_year, @month.to_i, @day.to_i)
return true
Expand Down Expand Up @@ -163,19 +187,19 @@ def luhn(str)
# Return Personnummer object from given string/integer with options
# (Personnummer)
def self.parse(personnummer, options={})
Personnummer.new(personnummer, options={})
Personnummer.new(personnummer, options)
end

# Check validity of string/integer input as Personnummer
# (TrueClass/FalseClass)
def self.valid?(personnummer, include_coord=true)
# Anything but a hash in place of the options is the old include_coord flag
def self.valid?(personnummer, options={})
options = {allow_coordination_number: !!options} unless options.is_a?(Hash)

begin
nummer = parse(personnummer)
if !include_coord && nummer.is_coord
return false
end
parse(personnummer, options)
true
rescue RuntimeError
rescue Error
false
end
end
Expand Down
109 changes: 109 additions & 0 deletions test/test_personnummer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,113 @@ def test_is_female
assert_equal false, Personnummer.parse('198507699810').is_female?
assert_equal true, Personnummer.parse('198507699802').is_female?
end

INTERIM_LETTERS = %w[T R S U W X J K L M N]
INTERIM_OPTS = {allow_interim_number: true}

def test_interim_valid_with_option
INTERIM_LETTERS.each do |l|
["20000101#{l}220", "000101#{l}220", "000101-#{l}220", "20000101-#{l}220"].each do |n|
assert_equal true, Personnummer.valid?(n, INTERIM_OPTS), n
end
end
assert_equal false, Personnummer.valid?('20000101E221', INTERIM_OPTS)
assert_equal false, Personnummer.valid?('000101-E221', INTERIM_OPTS)
end

def test_interim_rejected_by_default
INTERIM_LETTERS.each do |l|
assert_equal false, Personnummer.valid?("20000101#{l}220"), l
assert_equal false, Personnummer.valid?("000101-#{l}220"), l
assert_equal false, Personnummer.valid?("000101-#{l}220", allow_interim_number: false), l
assert_raises(Personnummer::Error) { Personnummer.parse("000101-#{l}220") }
end
end

def test_interim_format
INTERIM_LETTERS.each do |l|
["20000101#{l}220", "000101#{l}220", "000101-#{l}220", "20000101-#{l}220"].each do |n|
p = Personnummer.parse(n, INTERIM_OPTS)
assert_equal "000101-#{l}220", p.format, n
assert_equal "20000101#{l}220", p.format(true), n
end
end
end

def test_is_interim
INTERIM_LETTERS.each do |l|
assert_equal true, Personnummer.parse("20000101#{l}220", INTERIM_OPTS).is_interim
end
assert_equal false, Personnummer.parse('850709-9813').is_interim
assert_equal false, Personnummer.parse('850769-9810').is_interim
end

def test_interim_sex
assert_equal true, Personnummer.parse('000101-T220', INTERIM_OPTS).is_female?
assert_equal false, Personnummer.parse('000101-T220', INTERIM_OPTS).is_male?
end

def test_get_date
assert_equal Date.new(1985, 7, 9), Personnummer.parse('198507099805').get_date
assert_equal Date.new(1985, 7, 9), Personnummer.parse('850709-9813').get_date
assert_equal Date.new(1985, 7, 9), Personnummer.parse('198507699810').get_date
assert_equal Date.new(2000, 1, 1), Personnummer.parse('000101-T220', INTERIM_OPTS).get_date
end

def test_get_age_interim
Timecop.freeze(Time.utc(2020, "May", 1, 9, 0, 0)) do
assert_equal 20, Personnummer.parse('000101-T220', INTERIM_OPTS).get_age
end
end

def test_option_allow_coordination_number
assert_equal true, Personnummer.valid?('850769-9810', allow_coordination_number: true)
assert_equal false, Personnummer.valid?('850769-9810', allow_coordination_number: false)
assert_equal true, Personnummer.valid?('850709-9813', allow_coordination_number: false)
assert_equal true, Personnummer.parse('850769-9810').is_coord
assert_equal true, Personnummer.parse('850769-9810', allow_coordination_number: true).is_coord
assert_raises(Personnummer::Error) { Personnummer.parse('850769-9810', allow_coordination_number: false) }
assert_raises(Personnummer::Error) { Personnummer::Personnummer.new('850769-9810', allow_coordination_number: false) }
assert_equal false, Personnummer.parse('850709-9813', allow_coordination_number: false).is_coord
end

def test_option_allow_interim_number
assert_equal true, Personnummer.valid?('000101-T220', allow_interim_number: true)
assert_equal false, Personnummer.valid?('000101-T220', allow_interim_number: false)
assert_equal true, Personnummer.parse('000101-T220', allow_interim_number: true).is_interim
assert_raises(Personnummer::Error) { Personnummer::Personnummer.new('000101-T220') }
assert_equal true, Personnummer.valid?('850709-9813', allow_interim_number: true)
# Options combine
assert_equal true, Personnummer.valid?('000101-T220', allow_interim_number: true, allow_coordination_number: false)
assert_equal false, Personnummer.valid?('850769-9810', allow_interim_number: true, allow_coordination_number: false)
end

def test_valid_boolean_form
assert_equal true, Personnummer.valid?('850769-9810', true)
assert_equal false, Personnummer.valid?('850769-9810', false)
assert_equal true, Personnummer.valid?('850709-9813', false)
assert_equal false, Personnummer.valid?('000101-T220', true)
# The old flag was only tested for truthiness, and valid? must never raise.
assert_equal false, Personnummer.valid?('850769-9810', nil)
assert_equal true, Personnummer.valid?('850769-9810', 'yes')
end

def test_anchoring
assert_equal false, Personnummer.valid?('xx8507099805yy')
assert_equal false, Personnummer.valid?('xx198507099805')
assert_equal false, Personnummer.valid?('198507099805yy')
assert_equal false, Personnummer.valid?(" 198507099805")
assert_equal false, Personnummer.valid?("198507099805\n")
assert_equal false, Personnummer.valid?("x000101-T220", INTERIM_OPTS)
assert_equal false, Personnummer.valid?("000101-T220x", INTERIM_OPTS)
end

def test_error_class
assert_operator Personnummer::Error, :<, RuntimeError
error = assert_raises(Personnummer::Error) { Personnummer.parse('Just a string') }
assert_equal 'Could not parse Just a string as a valid Personnummer', error.message
error = assert_raises(Personnummer::Error) { Personnummer.parse('990919-3776') }
assert_equal 'Invalid Personnummer', error.message
assert_raises(RuntimeError) { Personnummer.parse('990919-3776') }
end
end
Loading