Class: Yapv::Pesel

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/yapv/pesel.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value = "") ⇒ Pesel

Returns a new instance of Pesel.



9
10
11
# File 'lib/yapv/pesel.rb', line 9

def initialize(value = "")
  self.value = value
end

Instance Attribute Details

#valueObject

Returns the value of attribute value.



4
5
6
# File 'lib/yapv/pesel.rb', line 4

def value
  @value
end

Instance Method Details

#birth_dateObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/yapv/pesel.rb', line 46

def birth_date
  return unless valid?
  case value[2].to_i
  when 0..1
    century = "19"
    offset = 0
  when 2..3
    century = "20"
    offset = 20
  when 4..5
    century = "21"
    offset = 40
  when 6..7
    century = "22"
    offset = 60
  when 8..9
    century = "18"
    offset = 80
  end

  year, month, day = value[0,6].scan(/\d\d/)
  month = month.to_i - offset
  Date.parse("#{century}#{year}-#{month}-#{day}")
end

#birth_date!Object

Raises:

  • (ArgumentError)


71
72
73
74
# File 'lib/yapv/pesel.rb', line 71

def birth_date!
  raise ArgumentError.new("PESEL is invalid") unless birth_date
  birth_date
end

#female?Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


41
42
43
44
# File 'lib/yapv/pesel.rb', line 41

def female?
  raise ArgumentError.new("PESEL is invalid") unless valid?
  gender == :female
end

#genderObject



26
27
28
29
# File 'lib/yapv/pesel.rb', line 26

def gender
  return unless valid?
  value[-2].to_i % 2 == 0 ? :female : :male
end

#gender!Object

Raises:

  • (ArgumentError)


31
32
33
34
# File 'lib/yapv/pesel.rb', line 31

def gender!
  raise ArgumentError.new("PESEL is invalid") unless gender
  gender
end

#male?Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


36
37
38
39
# File 'lib/yapv/pesel.rb', line 36

def male?
  raise ArgumentError.new("PESEL is invalid") unless valid?
  gender == :male
end

#pesel_formatObject



17
18
19
20
21
22
23
24
# File 'lib/yapv/pesel.rb', line 17

def pesel_format
  return unless value.length == 11
  mask = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]
  val = value.split("").map(&:to_i)

  modulo = mask.inject(0){|sum, num| sum + (num * val.shift)} % 10
  errors.add(:value) unless 10 - modulo == val.shift
end