Class: Snils
- Inherits:
-
Object
- Object
- Snils
- Defined in:
- lib/snils.rb,
lib/snils/version.rb
Overview
Generating, validating and formatting SNILS number Russian pension insurance individual account number)
Constant Summary collapse
- VERSION =
'0.1.2'
Class Method Summary collapse
-
.generate ⇒ Object
Generates new random valid SNILS.
-
.valid?(snils) ⇒ Boolean
Validates string with a SNILS.
Instance Method Summary collapse
-
#checksum ⇒ Object
Calculates checksum (last 2 digits) of a number.
-
#errors ⇒ Object
Returns array with errors if SNILS invalid.
-
#formatted ⇒ Object
Returns SNILS in format 000-000-000 00.
-
#initialize(number = nil) ⇒ Snils
constructor
New object with SNILS
numberif provided. -
#raw ⇒ Object
(also: #to_s)
Returns unformatted SNILS (only 11 digits).
-
#valid? ⇒ Boolean
Validates SNILS.
Constructor Details
#initialize(number = nil) ⇒ Snils
New object with SNILS number if provided. Otherwise, it generated randomly
7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/snils.rb', line 7 def initialize(number = nil) @snils = if number.kind_of? Numeric '%011d' % number elsif number number.to_s.gsub(/[^\d]/, '') else self.class.generate end @errors = [] @validated = false end |
Class Method Details
.generate ⇒ Object
Generates new random valid SNILS
61 62 63 64 65 |
# File 'lib/snils.rb', line 61 def self.generate digits = Array.new(9).map{ rand(10) }.join sum = self.new(digits).checksum "#{digits}#{sum}" end |
.valid?(snils) ⇒ Boolean
Validates string with a SNILS. Valid SNILS is a 11 digits long and have correct checksum.
39 40 41 |
# File 'lib/snils.rb', line 39 def self.valid?(snils) self.new(snils).valid? end |
Instance Method Details
#checksum ⇒ Object
Calculates checksum (last 2 digits) of a number
20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/snils.rb', line 20 def checksum digits = @snils.split('').take(9).map(&:to_i) checksum = digits.each.with_index.inject(0) do |sum, (digit, index)| sum + digit * (9 - index) end while checksum > 101 do checksum = checksum % 101 end checksum = 0 if (100..101).include?(checksum) '%02d' % checksum end |
#errors ⇒ Object
Returns array with errors if SNILS invalid
55 56 57 58 |
# File 'lib/snils.rb', line 55 def errors validate unless @validated @errors end |
#formatted ⇒ Object
Returns SNILS in format 000-000-000 00
44 45 46 |
# File 'lib/snils.rb', line 44 def formatted "#{@snils[0..2]}-#{@snils[3..5]}-#{@snils[6..8]} #{@snils[9..10]}" end |
#raw ⇒ Object Also known as: to_s
Returns unformatted SNILS (only 11 digits)
49 50 51 |
# File 'lib/snils.rb', line 49 def raw @snils end |
#valid? ⇒ Boolean
Validates SNILS. Valid SNILS is a 11 digits long and have correct checksum
33 34 35 36 |
# File 'lib/snils.rb', line 33 def valid? validate unless @validated @errors.none? end |