File: identification_fi.rb

package info (click to toggle)
ruby-ffaker 2.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,852 kB
  • sloc: ruby: 13,136; makefile: 8; sh: 1
file content (73 lines) | stat: -rw-r--r-- 2,321 bytes parent folder | download
1
2
3
4
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true

module FFaker
  module IdentificationFI
    extend ModuleUtils
    extend self

    CHECK_DIGITS = '0123456789ABCDEFHJKLMNPRSTUVWXY'
    # Number ranges in real use
    POSSIBLY_REAL_FEMALE_INDIVIDUAL_NUMBERS = (2..898).step(2).to_a.freeze
    POSSIBLY_REAL_MALE_INDIVIDUAL_NUMBERS = (3..899).step(2).to_a.freeze
    # Number ranges not in real use
    FAKE_FEMALE_INDIVIDUAL_NUMBERS = (900..998).step(2).to_a.freeze
    FAKE_MALE_INDIVIDUAL_NUMBERS = (901..999).step(2).to_a.freeze

    def identity_number(gender: FFaker::Gender.binary, birthday: FFaker::Date.birthday, fake: true)
      day = fetch_formatted_day(birthday)
      month = fetch_formatted_month(birthday)
      year = fetch_formatted_year(birthday)
      separator = fetch_separator(birthday)
      individual_number = fetch_individual_number(gender, fake)
      check_digit = calculate_check_digit(birthday, individual_number)
      "#{day}#{month}#{year}#{separator}#{individual_number}#{check_digit}"
    end

    private

    def fetch_formatted_day(birthday)
      format('%.2d', birthday.day)
    end

    def fetch_formatted_month(birthday)
      format('%.2d', birthday.month)
    end

    def fetch_formatted_year(birthday)
      check_birth_year(birthday.year)
      birthday.strftime('%y')
    end

    def fetch_separator(birthday)
      case birthday.year
      when ..1899
        '+'
      when 1900..1999
        '-'
      else
        'A'
      end
    end

    def fetch_individual_number(gender, fake)
      numbers_range = if gender == 'female'
                        fake ? FAKE_FEMALE_INDIVIDUAL_NUMBERS : POSSIBLY_REAL_FEMALE_INDIVIDUAL_NUMBERS
                      else
                        fake ? FAKE_MALE_INDIVIDUAL_NUMBERS : POSSIBLY_REAL_MALE_INDIVIDUAL_NUMBERS
                      end
      format('%.3d', fetch_sample(numbers_range))
    end

    def calculate_check_digit(birthday, individual_number)
      digit = "#{birthday.day}#{fetch_formatted_month(birthday)}#{fetch_formatted_year(birthday)}#{individual_number}"
              .to_i % 31
      CHECK_DIGITS[digit]
    end

    def check_birth_year(birth_year)
      return if birth_year.between?(1799, 2100)

      raise ArgumentError, "Birth year: #{birth_year} is not between supported 1799 and 2100 range"
    end
  end
end