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



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

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)


74
75
76
77
# File 'lib/yapv/pesel.rb', line 74

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

#female?Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


44
45
46
47
# File 'lib/yapv/pesel.rb', line 44

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

#genderObject



29
30
31
32
# File 'lib/yapv/pesel.rb', line 29

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

#gender!Object

Raises:

  • (ArgumentError)


34
35
36
37
# File 'lib/yapv/pesel.rb', line 34

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

#male?Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


39
40
41
42
# File 'lib/yapv/pesel.rb', line 39

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

#pesel_formatObject



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

def pesel_format
  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
  if modulo == 0
    errors.add(:value) unless val.shift == 0
  else
    errors.add(:value) unless 10 - modulo == val.shift
  end
end