Class: IdNumberLatam::ClDni

Inherits:
Base
  • Object
show all
Defined in:
lib/id_number_latam/cl_dni.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#country, #id_number, #unformatted_id_number

Instance Method Summary collapse

Methods inherited from Base

#get_dni_class

Constructor Details

#initialize(id_number, opts = {}) ⇒ ClDni

Returns a new instance of ClDni.



7
8
9
10
11
# File 'lib/id_number_latam/cl_dni.rb', line 7

def initialize(id_number, opts = {})
  super
  @country = :cl
  @digit   = unformat.slice(-1)
end

Instance Attribute Details

#digitObject (readonly)

Returns the value of attribute digit.



5
6
7
# File 'lib/id_number_latam/cl_dni.rb', line 5

def digit
  @digit
end

Instance Method Details

#formatObject



17
18
19
20
21
22
# File 'lib/id_number_latam/cl_dni.rb', line 17

def format
  dni = unformat
  digit = dni.slice!(-1)
  formatted_dni = dni.reverse.gsub(/(\d{3})(?=\d)/, '\\1.').reverse
  [formatted_dni, digit].join("-")
end

#unformatObject



13
14
15
# File 'lib/id_number_latam/cl_dni.rb', line 13

def unformat
  id_number.gsub(/\D/, "")
end

#valid?Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
# File 'lib/id_number_latam/cl_dni.rb', line 24

def valid?
  return false unless valid_length

  dni = unformat
  digit = dni.slice!(-1)

  [*0..9, "K"][dni.to_s.reverse.chars.inject([0, 0]) { |(i, a), n| [i + 1, a - n.to_i * (i % 6 + 2)] }[1] % 11].to_s == digit
end