Class: IdentityCode::PL

Inherits:
Object
  • Object
show all
Defined in:
lib/identity_code/pl.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code) ⇒ PL

Returns a new instance of PL.



45
46
47
# File 'lib/identity_code/pl.rb', line 45

def initialize(code)
  @code = code.to_s
end

Class Method Details

.control_digit(base) ⇒ Object



35
36
37
38
39
40
41
42
43
# 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 = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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

.valid?(code) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/identity_code/pl.rb', line 31

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

Instance Method Details

#ageObject



72
73
74
75
76
# 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_dateObject



54
55
56
57
58
59
60
# 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

#monthObject



62
63
64
65
66
67
68
69
70
# 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

#sexObject



78
79
80
81
# File 'lib/identity_code/pl.rb', line 78

def sex
  return unless valid?
  @code[9].to_i.odd? ? :M : :F
end

#valid?Boolean

Returns:

  • (Boolean)


49
50
51
52
# File 'lib/identity_code/pl.rb', line 49

def valid?
  @code.length == 11 &&
  @code[10].chr.to_i == self.class.control_digit(@code)
end