personnummer 0.1.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: 2d6e64825d8e5714d4e331370dbd8dfa7238bd45
4
- data.tar.gz: 60bbd44d98e1fc450db6461c11979236b1f5de96
2
+ SHA256:
3
+ metadata.gz: 3dcd80e850a666983b5212119f00f257477686d8e579508b3336274b359a1639
4
+ data.tar.gz: 5cf6b2f2fd0084a10d70dca28da9e6d366d81d0f703533a07aa10754a56f6bbd
5
5
  SHA512:
6
- metadata.gz: ac0b554f4d547f4b39e67698c8ea9615294167a5cae0292ed58084895cffaa0f23b6b399f9c4fe3e29488d4cdff565ba50459f9fa2c7d9e52312b9fa6212b2ac
7
- data.tar.gz: a24fb8d537c52d25756b31b6f7bb811bd405b6deaf193072757b46c9ff1960a5ad61b50d22b2d506580e3e1c3985129ea41d5ae0b8d99cbbf808ae9813f35d41
6
+ metadata.gz: 8d579a9dcfaa550c50aba9e5362f7f64b86e0d660255d4c0fbbc5a98eb5f732fa667e986d4361f485d40cbe0fdd02aaf41bf9ea8a7d6f225852e5e6736441b8e
7
+ data.tar.gz: 3bb1d3cd98280c6e7fb5d742d7363ef7190aebb310dd0c43ef96a993d5e9c4f537615b744bbba30f34956f67757ede243ff25a8fe15fd828744012a3f38fa6bb
@@ -0,0 +1,6 @@
1
+ {
2
+ "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3
+ "extends": [
4
+ "local>personnummer/.github:renovate-config"
5
+ ]
6
+ }
@@ -0,0 +1,41 @@
1
+
2
+ name: build
3
+
4
+ on:
5
+ push:
6
+ branches:
7
+ - main
8
+
9
+ # Run tests for any PRs.
10
+ pull_request:
11
+
12
+ jobs:
13
+ build:
14
+ runs-on: ubuntu-latest
15
+
16
+ strategy:
17
+ matrix:
18
+ # Quoted, since YAML would read an unquoted 4.0 as the number 4.
19
+ ruby-version: ['3.3', '3.4', '4.0']
20
+
21
+ steps:
22
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
23
+ - name: Set up Ruby ${{ matrix.ruby-version }}
24
+ uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0
25
+ with:
26
+ ruby-version: ${{ matrix.ruby-version }}
27
+ - name: gem install
28
+ run: gem install minitest timecop
29
+ - name: test
30
+ run: rake
31
+
32
+ # Single stable check for branch protection, so the ruleset does not need
33
+ # to change when the matrix does.
34
+ tests-passed:
35
+ if: always()
36
+ needs: [build]
37
+ runs-on: ubuntu-latest
38
+ steps:
39
+ - name: Fail if any test job failed or was cancelled
40
+ if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')
41
+ run: exit 1
data/.meta.yaml ADDED
@@ -0,0 +1,4 @@
1
+ name: "Ruby"
2
+ maintainer: "@VoxSecundus"
3
+ spec: 3.1
4
+ workflow: "ruby.yml"
data/LICENSE CHANGED
@@ -1,18 +1,21 @@
1
- Copyright (c) 2008 Peter Hellberg
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy of
4
- this software and associated documentation files (the "Software"), to deal in
5
- the Software without restriction, including without limitation the rights to
6
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
- the Software, and to permit persons to whom the Software is furnished to do so,
8
- subject to the following conditions:
9
-
1
+ MIT License
2
+
3
+ Copyright (c) 2017-2021 - Personnummer and Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
10
12
  The above copyright notice and this permission notice shall be included in all
11
13
  copies or substantial portions of the Software.
12
-
14
+
13
15
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # personnummer [![Build Status](https://github.com/personnummer/ruby/workflows/build/badge.svg)](https://github.com/personnummer/ruby/actions)
2
+
3
+ Validate personal identity numbers.
4
+
5
+ Versions 0.x of the `personnummer` gem are a different library, [c7/personnummer](https://github.com/c7/personnummer) by Peter Hellberg, who handed the gem name over to this project. They are still on RubyGems, and a Gemfile with `gem 'personnummer', '~> 0.1'` keeps getting them. The API there is `Personnummer.new('830428-5912').valid?`, here it is `Personnummer.valid?('830428-5912')`.
6
+
7
+ ## Installation
8
+
9
+ Add this to your `Gemfile`
10
+
11
+ ```
12
+ gem 'personnummer'
13
+ ```
14
+
15
+ Then run `bundle install`
16
+
17
+ ## Example
18
+
19
+ ```ruby
20
+ require 'personnummer'
21
+
22
+ Personnummer.valid?("8507099805")
23
+ # => true
24
+
25
+ pnr = Personnummer.parse("198507099805")
26
+ pnr.format # => "850709-9805"
27
+ pnr.format(true) # => "198507099805"
28
+ pnr.get_date.to_s # => "1985-07-09"
29
+ pnr.get_age # => 41 (in 2026)
30
+ pnr.is_female? # => true
31
+ pnr.is_coord # => false
32
+ pnr.is_interim # => false
33
+ ```
34
+
35
+ `parse` raises `Personnummer::Error` when the input is not a valid number.
36
+
37
+ ### Options
38
+
39
+ `parse` and `valid?` take an options hash.
40
+
41
+ | Option | Default | Description |
42
+ | --------------------------- | ------- | ------------------------------------------------ |
43
+ | `allow_coordination_number` | `true` | Accept coordination numbers (samordningsnummer). |
44
+ | `allow_interim_number` | `false` | Accept interim numbers (T-numbers). |
45
+
46
+ ```ruby
47
+ Personnummer.valid?("000101-T220")
48
+ # => false
49
+
50
+ Personnummer.valid?("000101-T220", allow_interim_number: true)
51
+ # => true
52
+
53
+ Personnummer.valid?("850769-9810", allow_coordination_number: false)
54
+ # => false
55
+ ```
56
+
57
+ See [test/test_personnummer.rb](test/test_personnummer.rb) for more examples.
58
+
59
+ ## In memoriam
60
+
61
+ Fredrik "Frozzare" Forsmo (1991-2026) was the initiator, co-founder and a core contributor of the personnummer project. This library carries his work. He is missed.
62
+
63
+ ## License
64
+
65
+ MIT
data/Rakefile CHANGED
@@ -1,6 +1,8 @@
1
- require 'bundler/gem_tasks'
1
+ require 'rake/testtask'
2
2
 
3
- require 'rspec/core/rake_task'
4
- RSpec::Core::RakeTask.new(:spec)
3
+ Rake::TestTask.new do |t|
4
+ t.libs << 'test'
5
+ end
5
6
 
6
- task :default => :spec
7
+ desc 'Run tests'
8
+ task :default => :test
data/lib/personnummer.rb CHANGED
@@ -1,216 +1,206 @@
1
1
  # -*- encoding: utf-8 -*-
2
2
  require 'date'
3
3
 
4
- class Personnummer
5
- # Public readonly attributes
6
- attr_reader :region, :control_digit
7
-
8
- def initialize(number)
9
- @valid = false
10
-
11
- # Match the number
12
- number = number.to_s
13
-
14
- if number.match(/(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\-\+]{0,1})(\d{3})(\d{0,1})/)
15
- # Calculate the control digit based on the birth date and serial number
16
- cd = luhn_algorithm("#{$~[2]}#{$~[3]}#{$~[4]}#{$~[6]}")
17
-
18
- # Set control digit to calculated if it's missing
19
- @control_digit = $~[7].nil? || $~[7].empty? ? cd : $~[7].to_i
20
-
21
- # Get the different parts of the number
22
- century = $~[1].to_i
23
- year = $~[2].to_i
24
- month = $~[3].to_i
25
- day = $~[4].to_i
26
- @divider = $~[5]
27
- @serial = $~[6].to_i
28
-
29
- # Set default divider if not present
30
- if @divider.empty?
31
- @divider = '-'
4
+ module Personnummer
5
+ # Inherits from RuntimeError so existing `rescue RuntimeError` keeps working
6
+ class Error < RuntimeError; end
7
+
8
+ DEFAULT_OPTIONS = {
9
+ allow_coordination_number: true,
10
+ allow_interim_number: false
11
+ }.freeze
12
+
13
+ class Personnummer
14
+ def initialize(personnummer, options={})
15
+ parts = get_parts(personnummer)
16
+ # Create instance variable and getter/setter for each pair in `parts` hash
17
+ parts.each do |k,v|
18
+ instance_variable_set("@#{k}", v)
19
+ eigenclass = class<<self; self; end
20
+ eigenclass.class_eval do
21
+ attr_accessor k
22
+ end
32
23
  end
24
+ @options = DEFAULT_OPTIONS.merge(options || {})
33
25
 
34
- # Make the personnummer valid if the checksum is correct
35
- @valid = true if @control_digit == cd && !$~[7].empty?
36
-
37
- @born = Born.new(century, year, month, day, @divider)
38
- @valid = @born.valid? && @valid
26
+ if !valid
27
+ raise Error, "Invalid Personnummer"
28
+ end
39
29
 
40
- # Get the region name
41
- @region = region_name(@serial)
30
+ if !@options[:allow_coordination_number] && is_coord
31
+ raise Error, "Coordination numbers are not allowed"
32
+ end
42
33
 
43
- # Check if the person is female based the serial (even == female)
44
- @female = (@serial % 2 == 0)
45
- else
46
- raise ArgumentError.new, "The supplied personnummer is invalid"
34
+ if !@options[:allow_interim_number] && is_interim
35
+ raise Error, "Interim numbers are not allowed"
36
+ end
47
37
  end
48
- end
49
-
50
- def age
51
- @born.age
52
- end
53
-
54
- def born
55
- @born.to_date
56
- end
57
-
58
- def ==(other)
59
- other = self.class.new(other) if other.is_a?(String) || other.is_a?(Integer)
60
-
61
- to_s == other.to_s
62
- end
63
-
64
- def to_s
65
- born_string = born.strftime("%y%m%d")
66
38
 
67
- if co_ordination_number?
68
- day = born_string[4..6].to_i + 60
69
- born_string = [born_string[0..3], "%02d" % day].join
39
+ # Checks if the Personnummer is a coordination number (Samordningsnummer)
40
+ # (TrueClass/FalseClass)
41
+ def is_coord
42
+ test_date(full_year, @month.to_i, @day.to_i - 60)
70
43
  end
71
44
 
72
- "%s%s%03d%d" % [born_string, @divider, @serial, @control_digit]
73
- end
74
-
75
- def valid?
76
- @valid
77
- end
78
-
79
- def male?
80
- !@female
81
- end
45
+ # Checks if the Personnummer is an interim number (T-nummer)
46
+ # (TrueClass/FalseClass)
47
+ def is_interim
48
+ @num.match?(/\A[TRSUWXJKLMN]/)
49
+ end
82
50
 
83
- def female?
84
- @female
85
- end
51
+ # Returns the short/long formatted number
52
+ def format(long_format=false)
53
+ if long_format
54
+ [@century,@year,@month,@day,@num,@check].join
55
+ else
56
+ [@year,@month,@day,@sep,@num,@check].join
57
+ end
58
+ end
86
59
 
87
- def co_ordination_number?
88
- @born.co_ordination_number?
89
- end
60
+ # Returns the age of the Personnummer's owner
61
+ # (Integer)
62
+ def get_age
63
+ today = Time.new
64
+ date = get_date
90
65
 
91
- private
66
+ return today.year - date.year - ((today.month > date.month || (today.month == date.month && today.day >= date.day)) ? 0 : 1)
67
+ end
92
68
 
93
- def luhn_algorithm(number)
94
- multiplications = []
69
+ # Returns the date of birth, with the 60 day offset of coordination numbers removed
70
+ # (Date)
71
+ def get_date
72
+ day = @day.to_i
73
+ day -= 60 if is_coord
95
74
 
96
- number.split(//).each_with_index do |digit, i|
97
- if i % 2 == 0
98
- multiplications << digit.to_i*2
99
- else
100
- multiplications << digit.to_i
101
- end
75
+ Date.new(full_year, @month.to_i, day)
102
76
  end
103
77
 
104
- sum = 0
105
-
106
- multiplications.each do |num|
107
- num.to_s.each_byte do |character|
108
- sum += character.chr.to_i
109
- end
78
+ # Checks if the Personnummer's owner is male
79
+ # (TrueClass/FalseClass)
80
+ def is_male?
81
+ sexDigit = @num[-1].to_i
82
+ sexDigit % 2 == 1
110
83
  end
111
84
 
112
- if sum % 10 == 0
113
- control_digit = 0
114
- else
115
- control_digit = (sum / 10 + 1) * 10 - sum
85
+ # Checks if the Personnummer's owner is female
86
+ # (TrueClass/FalseClass)
87
+ def is_female?
88
+ !is_male?
116
89
  end
117
90
 
118
- control_digit
119
- end
91
+ private
120
92
 
121
- def region_name(code)
122
- # Don't return a region name if the person was born after 1990
123
- # (When the previous region code was changed to a serial number)
124
- if @born.year > 1990
125
- return ''
126
- end
93
+ # Regex magic to split the input into parts hash.
94
+ # Raises Error if regex is refused.
95
+ # (Hash)
96
+ def get_parts(personnummer)
97
+ reg = /\A(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([\+\-]?)((?!000)\d{3}|[TRSUWXJKLMN]\d{2})(\d)\z/
98
+ match = personnummer.to_s.match(reg)
127
99
 
128
- case code
129
- when 000..139 then 'Stockholms Län'
130
- when 140..159 then 'Uppsala län'
131
- when 160..189 then 'Södermanlands län'
132
- when 190..239 then 'Östergötlands län'
133
- when 240..269 then 'Jönköpings län'
134
- when 270..289 then 'Kronobergs län'
135
- when 290..319 then 'Kalmar län'
136
- when 320..329 then 'Gotlands län'
137
- when 330..349 then 'Blekinge län'
138
- when 350..389 then 'Kristianstads län'
139
- when 390..459 then 'Malmöhus län'
140
- when 460..479 then 'Hallands län'
141
- when 480..549 then 'Göteborgs och Bohus län'
142
- when 550..589 then 'Älvsborgs län'
143
- when 590..619 then 'Skaraborgs län'
144
- when 620..649 then 'Värmlands län'
145
- when 650..659 then 'Födda utomlands'
146
- when 660..689 then 'Örebro län'
147
- when 690..709 then 'Västmanlands län'
148
- when 710..739 then 'Kopparbergs län'
149
- when 750..779 then 'Gävleborgs län'
150
- when 780..819 then 'Västernorrlands län'
151
- when 820..849 then 'Jämtlands län'
152
- when 850..889 then 'Västerbottens län'
153
- when 890..929 then 'Norrbottens län'
154
- when 930..999 then 'Födda utomlands eller utländska medborgare födda i Sverige'
155
- end
156
- end
100
+ if !match
101
+ raise Error, "Could not parse #{personnummer} as a valid Personnummer"
102
+ end
157
103
 
158
- class Born
159
- attr_reader :year, :month
104
+ century = match[1]
105
+ year = match[2]
106
+ month = match[3]
107
+ day = match[4]
108
+ sep = match[5]
109
+ num = match[6]
110
+ check = match[7]
111
+
112
+ if !century
113
+ base_year = Time.new.year
114
+ if sep == '+'
115
+ base_year -= 100
116
+ else
117
+ sep = '-'
118
+ end
119
+ full_year = base_year - ((base_year - year.to_i) % 100)
120
+ century = (full_year / 100).to_s
121
+ else
122
+ if Time.new.year - (century + year).to_i < 100
123
+ sep = '-'
124
+ else
125
+ sep = '+'
126
+ end
127
+ end
160
128
 
161
- def initialize(century, year, month, day, divider)
162
- @divider = divider
163
- @day = day
164
- @month = month
165
- @year = calculate_century(century, year) + year
129
+ return {
130
+ century: century,
131
+ year: year,
132
+ month: month,
133
+ day: day,
134
+ sep: sep,
135
+ num: num,
136
+ check: check
137
+ }
166
138
  end
167
139
 
168
- def day
169
- co_ordination_number? ? @day - 60 : @day
140
+ # With the century, since e.g. 1900 is not a leap year, but year 0 is.
141
+ # (Integer)
142
+ def full_year
143
+ "#{@century}#{@year}".to_i
170
144
  end
171
145
 
172
- def co_ordination_number?
173
- @day && 60 < @day and @day < 92
146
+ # Checks if the given values form a valid date
147
+ # (TrueClass/FalseClass)
148
+ def test_date(year, month, day)
149
+ # Date.valid_date? counts negative days from the end of the month, so e.g. day 30 - 60 would pass.
150
+ day > 0 && Date.valid_date?(year, month, day)
174
151
  end
175
152
 
176
- def to_date
177
- Date.parse("#{year}-#{month}-#{day}")
178
- end
153
+ # Checks if the Personnummer is valid
154
+ # (TrueClass/FalseClass)
155
+ def valid
156
+ if @check.length == 0
157
+ return false
158
+ end
179
159
 
180
- def valid?
181
- to_date && true
182
- end
160
+ is_valid = luhn(@year + @month + @day + @num.sub(/\A[TRSUWXJKLMN]/, '1')) == @check.to_i
183
161
 
184
- def age
185
- if Date.today > to_date
186
- (Date.today - to_date).to_i/365
187
- else
188
- 0
162
+ if is_valid && test_date(full_year, @month.to_i, @day.to_i)
163
+ return true
189
164
  end
165
+
166
+ return is_valid && test_date(full_year, @month.to_i, @day.to_i - 60)
190
167
  end
191
168
 
192
- private
169
+ # Implementation of Luhn algorithm for calculating Personnummer checksum
170
+ # (Integer)
171
+ def luhn(str)
172
+ sum = 0
193
173
 
194
- def calculate_century(century, year)
195
- # Get the current date
196
- today = Date.today
197
-
198
- if century == 0
199
- # Decide which century corresponds to the number
200
- if year < (today.year-2000) && @divider == '-'
201
- century = 2000
202
- elsif year < (today.year-2000) && @divider == '+'
203
- century = 1900
204
- elsif @divider == '+'
205
- century = 1800
206
- else
207
- century = 1900
174
+ for i in 0...str.length
175
+ v = str[i].to_i
176
+ v *= 2 - (i % 2)
177
+ if v > 9
178
+ v -= 9
208
179
  end
209
- else
210
- century *= 100
180
+ sum += v
211
181
  end
212
182
 
213
- return century
183
+ ((sum.to_f / 10).ceil * 10 - sum.to_f).to_i
184
+ end
185
+ end
186
+
187
+ # Return Personnummer object from given string/integer with options
188
+ # (Personnummer)
189
+ def self.parse(personnummer, options={})
190
+ Personnummer.new(personnummer, options)
191
+ end
192
+
193
+ # Check validity of string/integer input as Personnummer
194
+ # (TrueClass/FalseClass)
195
+ # Anything but a hash in place of the options is the old include_coord flag
196
+ def self.valid?(personnummer, options={})
197
+ options = {allow_coordination_number: !!options} unless options.is_a?(Hash)
198
+
199
+ begin
200
+ parse(personnummer, options)
201
+ true
202
+ rescue Error
203
+ false
214
204
  end
215
205
  end
216
206
  end
data/personnummer.gemspec CHANGED
@@ -2,25 +2,22 @@
2
2
  $:.push File.expand_path("../lib", __FILE__)
3
3
 
4
4
  Gem::Specification.new do |s|
5
- s.name = "personnummer"
6
- s.version = "0.1.0"
7
- s.authors = ["Peter Hellberg", "Victor Koronen", "Jacob Burenstam", "Sebastian Wallin", "Jens Carlén"]
8
- s.email = ["peter@c7.se"]
9
- s.homepage = "https://github.com/c7/personnummer/"
10
- s.summary = %q{Personnummer handles validation of Swedish personal identity numbers.}
11
- s.description = %q{Personnummer handles validation of Swedish personal identity numbers.}
12
-
13
- s.has_rdoc = false
14
-
15
- s.files = `git ls-files`.split("\n")
16
- s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
- s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
18
- s.require_paths = ["lib"]
19
-
20
- s.add_development_dependency "rake"
21
- s.add_development_dependency "rspec"
22
- s.add_development_dependency "guard"
23
- s.add_development_dependency "guard-bundler"
24
- s.add_development_dependency "guard-rspec"
25
- s.add_development_dependency "timecop"
26
- end
5
+ s.name = 'personnummer'
6
+ s.version = '3.1.0'
7
+ s.date = '2026-11-13'
8
+ s.summary = 'Validate Swedish social security numbers'
9
+ s.description = 'Validate Swedish social security numbers'
10
+ s.authors = ['Jack Millard']
11
+ s.email = ['millard64@hotmail.co.uk']
12
+ s.files = `git ls-files`.split("\n")
13
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
14
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
15
+ s.require_paths = ["lib"]
16
+ s.homepage = 'https://github.com/personnummer/ruby'
17
+ s.license = 'MIT'
18
+ # The oldest Ruby in the CI matrix.
19
+ s.required_ruby_version = '>= 3.3'
20
+ s.add_development_dependency 'rake'
21
+ s.add_development_dependency 'minitest'
22
+ s.add_development_dependency 'timecop'
23
+ end