Class: Snils

Inherits:
Object
  • Object
show all
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.1'

Class Method Summary collapse

Instance Method Summary collapse

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

.generateObject

Generates new random valid SNILS



65
66
67
68
69
# File 'lib/snils.rb', line 65

def self.generate
  digits = Array.new(9).map{ rand (0..9) }.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.

Returns:

  • (Boolean)


43
44
45
# File 'lib/snils.rb', line 43

def self.valid?(snils)
  self.new(snils).valid?
end

Instance Method Details

#checksumObject

Calculates checksum (last 2 digits) of a number



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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
  checksum = case
               when (100..101).cover?(checksum)
                 0
               when checksum > 101
                 checksum % 101
               else
                 checksum
             end
  '%02d' % checksum
end

#errorsObject

Returns array with errors if SNILS invalid



59
60
61
62
# File 'lib/snils.rb', line 59

def errors
  validate  unless @validated
  @errors
end

#formattedObject

Returns SNILS in format 000-000-000 00



48
49
50
# File 'lib/snils.rb', line 48

def formatted
  "#{@snils[0..2]}-#{@snils[3..5]}-#{@snils[6..8]} #{@snils[9..10]}"
end

#rawObject Also known as: to_s

Returns unformatted SNILS (only 11 digits)



53
54
55
# File 'lib/snils.rb', line 53

def raw
  @snils
end

#valid?Boolean

Validates SNILS. Valid SNILS is a 11 digits long and have correct checksum

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/snils.rb', line 37

def valid?
  validate  unless @validated
  @errors.none?
end