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.2.0'

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



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.

Returns:

  • (Boolean)


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

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
# File 'lib/snils.rb', line 20

def checksum
  digits = @snils.split('').take(9).map(&:to_i)
  checksum = digits.each.with_index.reduce(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

#errorsObject

Returns array with errors if SNILS invalid



55
56
57
58
# File 'lib/snils.rb', line 55

def errors
  validate  unless @validated
  @errors
end

#formattedObject

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

#rawObject 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

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/snils.rb', line 33

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