class Snils
Generating, validating and formatting SNILS number Russian pension insurance individual account number)
Constants
- VERSION
Public Class Methods
generate(num = nil)
click to toggle source
Generates new random valid SNILS
if you'll provide num
, it will be used as a base for new SNILS, checksum will be calculated automatically.
# File lib/snils.rb, line 64 def self.generate(num = nil) digits = num.nil? ? Array.new(9).map { rand(10) }.join : ('%09d' % num) sum = self.new(digits).checksum "#{digits}#{sum}" end
new(number = nil)
click to toggle source
New object with SNILS number
if provided. Otherwise, it generated randomly
# 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
valid?(snils)
click to toggle source
Validates string with a SNILS. Valid SNILS is a 11 digits long and have correct checksum.
# File lib/snils.rb, line 39 def self.valid?(snils) self.new(snils).valid? end
Public Instance Methods
checksum()
click to toggle source
Calculates checksum (last 2 digits) of a number
# 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
errors()
click to toggle source
Returns array with errors if SNILS invalid
# File lib/snils.rb, line 55 def errors validate unless @validated @errors end
formatted()
click to toggle source
Returns SNILS in format 000-000-000 00
# File lib/snils.rb, line 44 def formatted "#{@snils[0..2]}-#{@snils[3..5]}-#{@snils[6..8]} #{@snils[9..10]}" end
raw()
click to toggle source
Returns unformatted SNILS (only 11 digits)
# File lib/snils.rb, line 49 def raw @snils end
Also aliased as: to_s
valid?()
click to toggle source
Validates SNILS. Valid SNILS is a 11 digits long and have correct checksum
# File lib/snils.rb, line 33 def valid? validate unless @validated @errors.none? end
Protected Instance Methods
validate()
click to toggle source
# File lib/snils.rb, line 72 def validate @errors << [:wrong_length, { :count => 11 }] unless @snils.length == 11 @errors << :invalid unless @snils[-2..-1] == self.checksum @validated = true end