class IdentityCode::PL

Public Class Methods

control_digit(base) click to toggle source
# File lib/identity_code/pl.rb, line 35
def self.control_digit(base)
  multipliers = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7]
  id_ary = base.split(//).map(&:to_i)
  sum = 0

  (0...multipliers.count).each { |i| sum += id_ary[i] * multipliers[i] }

  sum % 10
end
generate(opts = {}) click to toggle source
# File lib/identity_code/pl.rb, line 5
def self.generate(opts = {})
  sex = opts[:sex] || (rand.round == 0 ? :M : :F)
  year = opts[:year] || rand(Date.today.year - 90..Date.today.year - 1)
  year = rand(Date.today.year - 50..Date.today.year - 21) if opts[:safe_age]
  month = opts[:month] || rand(1..12)
  calc_month = begin
    offset = case year.to_s[0..1]
      when '18' then 80
      when '19' then 0
      when '20' then 20
    end
    month + offset
  end
  day = opts[:day] || rand(1..NUM_DAYS[month])

  sex_digit = [0, 2, 4, 6, 8].sample
  sex_digit += 1 if sex.upcase.to_sym == :M

  result  = "%02d" % year.to_s[2..3].to_i
  result += "%02d" % calc_month
  result += "%02d" % day
  result += "%03d" % rand(1..999)
  result += sex_digit.to_s
  result += control_digit(result).to_s
end
new(code) click to toggle source
# File lib/identity_code/pl.rb, line 45
def initialize(code)
  @code = code.to_s
end
valid?(code) click to toggle source
# File lib/identity_code/pl.rb, line 31
def self.valid?(code)
  new(code).valid?
end

Public Instance Methods

age() click to toggle source
# File lib/identity_code/pl.rb, line 72
def age
  return unless valid?
  now = Time.now.utc.to_date
  now.year - (birth_date.year + IdentityCode::age_correction(birth_date))
end
birth_date() click to toggle source
# File lib/identity_code/pl.rb, line 54
def birth_date
  return unless valid?
  year = century + @code[0..1].to_i
  day = @code[4..5].to_i
  return unless Date.valid_date?(year, month, day)
  Date.new(year, month, day)
end
month() click to toggle source
# File lib/identity_code/pl.rb, line 62
def month
  raw_num = @code[2..3].to_i

  case raw_num
  when 81..92 then raw_num - 80
  when 1..12  then raw_num
  when 21..32 then raw_num - 20
  end
end
sex() click to toggle source
# File lib/identity_code/pl.rb, line 78
def sex
  return unless valid?
  @code[9].to_i.odd? ? :M : :F
end
valid?() click to toggle source
# File lib/identity_code/pl.rb, line 49
def valid?
  @code.length == 11 &&
  @code[10].chr.to_i == self.class.control_digit(@code)
end

Private Instance Methods

century() click to toggle source
# File lib/identity_code/pl.rb, line 85
def century
  c = @code[2..3].to_i

  case c
  when 81..92 then 1800
  when 1..12  then 1900
  when 21..32 then 2000
  end
end